Example usage for com.itextpdf.text Rectangle getTop

List of usage examples for com.itextpdf.text Rectangle getTop

Introduction

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

Prototype

public float getTop() 

Source Link

Document

Returns the upper right y-coordinate.

Usage

From source file:ihm.panneaux.GenererPdf.java

public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
    PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
    if (top != null) {
        canvas.saveState();//w ww.j a  v a2s  .  co  m
        top.applyLineDash(canvas);
        canvas.moveTo(position.getRight(), position.getTop());
        canvas.lineTo(position.getLeft(), position.getTop());
        canvas.stroke();
        canvas.restoreState();
    }
    if (bottom != null) {
        canvas.saveState();
        bottom.applyLineDash(canvas);
        canvas.moveTo(position.getRight() - 35, position.getBottom());
        canvas.lineTo(position.getLeft(), position.getBottom());
        canvas.stroke();
        canvas.restoreState();
    }
    if (right != null) {
        canvas.saveState();
        right.applyLineDash(canvas);
        canvas.moveTo(position.getRight(), position.getTop());
        canvas.lineTo(position.getRight(), position.getBottom());
        canvas.stroke();
        canvas.restoreState();
    }
    if (left != null) {
        canvas.saveState();
        left.applyLineDash(canvas);
        canvas.moveTo(position.getLeft(), position.getTop());
        canvas.lineTo(position.getLeft(), position.getBottom());
        canvas.stroke();
        canvas.restoreState();
    }
}

From source file:ke.co.tawi.babblesms.server.utils.export.PdfUtil.java

License:Open Source License

/**
 * Adds the header and the footer./*from  w ww  .  j  a va  2 s.c  om*/
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
 *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {
    Rectangle rect = writer.getBoxSize("art");
    switch (writer.getPageNumber() % 1) {

    case 0:
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, header[0], rect.getRight(),
                rect.getTop(), 0);
        break;
    case 1:
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, header[1], rect.getLeft(),
                rect.getTop(), 0);
        break;
    }
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
            new Phrase(String.format("page %d", pagenumber)), (rect.getLeft() + rect.getRight()) / 2,
            rect.getBottom() - 18, 0);
}

From source file:memoire.HeaderAndFooterPdfPageEventHelper.java

public void onStartPage(PdfWriter pdfWriter, Document document, String HeaderString) {
    System.out.println("onStartPage() method > Writing header in file");
    Rectangle rect = pdfWriter.getBoxSize("rectangle");

    // TOP LEFT//from   w  ww.j av a 2 s  . c  o m
    ColumnText.showTextAligned(pdfWriter.getDirectContent(), Element.ALIGN_CENTER, new Phrase(""),
            rect.getLeft(), rect.getTop(), 0);

    // TOP MEDIUM
    ColumnText.showTextAligned(pdfWriter.getDirectContent(), Element.ALIGN_CENTER, new Phrase(HeaderString),
            rect.getRight() / 2, rect.getTop(), 0);

    // TOP RIGHT
    ColumnText.showTextAligned(pdfWriter.getDirectContent(), Element.ALIGN_CENTER, new Phrase(""),
            rect.getRight(), rect.getTop(), 0);
}

From source file:mkl.testarea.itext5.pdfcleanup.PdfCleanUpRegionFilter.java

License:Open Source License

private Point2D[] getVertices(Rectangle rect) {
    Point2D[] points = { new Point2D.Double(rect.getLeft(), rect.getBottom()),
            new Point2D.Double(rect.getRight(), rect.getBottom()),
            new Point2D.Double(rect.getRight(), rect.getTop()),
            new Point2D.Double(rect.getLeft(), rect.getTop()) };

    return points;
}

From source file:mkl.testarea.itext5.pdfcleanup.PdfCleanUpRegionFilter.java

License:Open Source License

/**
 * Transforms the given Rectangle into the image coordinate system which is [0,1]x[0,1] by default
 *///  ww w  . ja  v a2  s  .  co m
private Rectangle transformIntersection(Matrix imageCTM, Rectangle rect) {
    Point2D[] points = transformPoints(imageCTM, true, new Point(rect.getLeft(), rect.getBottom()),
            new Point(rect.getLeft(), rect.getTop()), new Point(rect.getRight(), rect.getBottom()),
            new Point(rect.getRight(), rect.getTop()));
    return getRectangle(points[0], points[1], points[2], points[3]);
}

From source file:mkl.testarea.itext5.pdfcleanup.PdfCleanUpRenderListener.java

License:Open Source License

private void cleanImage(BufferedImage image, List<Rectangle> areasToBeCleaned) {
    Graphics2D graphics = image.createGraphics();
    graphics.setColor(CLEANED_AREA_FILL_COLOR);

    // A rectangle in the areasToBeCleaned list is treated to be in standard [0, 1]x[0,1] image space
    // (y varies from bottom to top and x from left to right), so we should scale the rectangle and also
    // invert and shear the y axe
    for (Rectangle rect : areasToBeCleaned) {
        int scaledBottomY = (int) Math.ceil(rect.getBottom() * image.getHeight());
        int scaledTopY = (int) Math.floor(rect.getTop() * image.getHeight());

        int x = (int) Math.ceil(rect.getLeft() * image.getWidth());
        int y = scaledTopY * -1 + image.getHeight();
        int width = (int) Math.floor(rect.getRight() * image.getWidth()) - x;
        int height = scaledTopY - scaledBottomY;

        graphics.fillRect(x, y, width, height);
    }//from   w  w w  .  j  a  v a2  s . c o m

    graphics.dispose();
}

From source file:mkl.testarea.itext5.pdfcleanup.StrictPdfCleanUpProcessor.java

License:Open Source License

private void addColoredRectangle(PdfContentByte canvas, PdfCleanUpLocation cleanUpLocation) {
    Rectangle cleanUpRegion = cleanUpLocation.getRegion();

    canvas.saveState();// w  ww  .j a  v  a 2  s . c  om
    canvas.setColorFill(cleanUpLocation.getCleanUpColor());
    canvas.moveTo(cleanUpRegion.getLeft(), cleanUpRegion.getBottom());
    canvas.lineTo(cleanUpRegion.getRight(), cleanUpRegion.getBottom());
    canvas.lineTo(cleanUpRegion.getRight(), cleanUpRegion.getTop());
    canvas.lineTo(cleanUpRegion.getLeft(), cleanUpRegion.getTop());
    canvas.closePath();
    canvas.fill();
    canvas.restoreState();
}

From source file:net.pflaeging.PortableSigner.PDFSigner.java

License:Open Source License

/** Creates a new instance of DoSignPDF */
public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password,
        Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment,
        String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin,
        float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException {
    try {// w ww .j  a v a  2 s. c  om
        //System.out.println("-> DoSignPDF <-");
        //System.out.println("Eingabedatei: " + pdfInputFileName);
        //System.out.println("Ausgabedatei: " + pdfOutputFileName);
        //System.out.println("Signaturdatei: " + pkcs12FileName);
        //System.out.println("Signaturblock?: " + signText);
        //System.out.println("Sprache der Blocks: " + signLanguage);
        //System.out.println("Signaturlogo: " + sigLogo);
        System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin);
        Rectangle signatureBlock;

        java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);

        pkcs12 = new GetPKCS12(pkcs12FileName, password);

        PdfReader reader = null;
        try {
            //                System.out.println("Password:" + ownerPassword.toString());
            if (ownerPassword == null)
                reader = new PdfReader(pdfInputFileName);
            else
                reader = new PdfReader(pdfInputFileName, ownerPassword);
        } catch (IOException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle(
                "net/pflaeging/PortableSigner/i18n").getString(
                "CouldNotBeOpened"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeOpened"), true, e.getLocalizedMessage());
        }
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(pdfOutputFileName);
        } catch (FileNotFoundException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeWritten"), true, e.getLocalizedMessage());

        }
        PdfStamper stp = null;
        try {
            Date datum = new Date(System.currentTimeMillis());

            int pages = reader.getNumberOfPages();

            Rectangle size = reader.getPageSize(pages);
            stp = PdfStamper.createSignature(reader, fout, '\0', null, true);
            HashMap<String, String> pdfInfo = reader.getInfo();
            // thanks to Markus Feisst
            String pdfInfoProducer = "";

            if (pdfInfo.get("Producer") != null) {
                pdfInfoProducer = pdfInfo.get("Producer").toString();
                pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")";
            } else {
                pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")";
            }
            pdfInfo.put("Producer", pdfInfoProducer);
            //System.err.print("++ Producer:" + pdfInfo.get("Producer").toString());
            stp.setMoreInfo(pdfInfo);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XmpWriter xmp = new XmpWriter(baos, pdfInfo);
            xmp.close();
            stp.setXmpMetadata(baos.toByteArray());
            if (signText) {
                String greet, signator, datestr, ca, serial, special, note, urn, urnvalue;
                int specialcount = 0;
                int sigpage;
                int rightMarginPT, leftMarginPT;
                float verticalPositionPT;
                ResourceBundle block = ResourceBundle
                        .getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage);
                greet = block.getString("greeting");
                signator = block.getString("signator");
                datestr = block.getString("date");
                ca = block.getString("issuer");
                serial = block.getString("serial");
                special = block.getString("special");
                note = block.getString("note");
                urn = block.getString("urn");
                urnvalue = block.getString("urnvalue");

                //sigcomment = block.getString(signLanguage + "-comment");
                // upper y
                float topy = size.getTop();
                System.err.println("Top: " + topy * ptToCm);
                // right x
                float rightx = size.getRight();
                System.err.println("Right: " + rightx * ptToCm);
                if (!noExtraPage) {
                    sigpage = pages + 1;
                    stp.insertPage(sigpage, size);
                    // 30pt left, 30pt right, 20pt from top
                    rightMarginPT = 30;
                    leftMarginPT = 30;
                    verticalPositionPT = topy - 20;
                } else {
                    if (signLastPage) {
                        sigpage = pages;
                    } else {
                        sigpage = 1;
                    }
                    System.err.println("Page: " + sigpage);
                    rightMarginPT = Math.round(rightMargin / ptToCm);
                    leftMarginPT = Math.round(leftMargin / ptToCm);
                    verticalPositionPT = topy - Math.round(verticalPos / ptToCm);
                }
                if (!GetPKCS12.atEgovOID.equals("")) {
                    specialcount = 1;
                }
                PdfContentByte content = stp.getOverContent(sigpage);

                float[] cellsize = new float[2];
                cellsize[0] = 100f;
                // rightx = width of page
                // 60 = 2x30 margins
                // cellsize[0] = description row
                // cellsize[1] = 0
                // 70 = logo width
                cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70;

                // Pagetable = Greeting, signatureblock, comment
                // sigpagetable = outer table
                //      consist: greetingcell, signatureblock , commentcell
                PdfPTable signatureBlockCompleteTable = new PdfPTable(2);
                PdfPTable signatureTextTable = new PdfPTable(2);
                PdfPCell signatureBlockHeadingCell = new PdfPCell(
                        new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12))));
                signatureBlockHeadingCell.setPaddingBottom(5);
                signatureBlockHeadingCell.setColspan(2);
                signatureBlockHeadingCell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(signatureBlockHeadingCell);

                // inner table start
                // Line 1
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10))));
                // Line 2
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 3
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10))));
                // Line 4
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(new Paragraph(
                        new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 5
                if (specialcount == 1) {
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10))));
                }
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable
                        .addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10))));
                signatureTextTable.setTotalWidth(cellsize);
                System.err.println(
                        "signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm);
                // inner table end

                signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                Image logo;
                //                     System.out.println("Logo:" + sigLogo + ":");
                if (sigLogo == null || "".equals(sigLogo)) {
                    logo = Image.getInstance(
                            getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png"));
                } else {
                    logo = Image.getInstance(sigLogo);
                }

                PdfPCell logocell = new PdfPCell();
                logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                logocell.setImage(logo);
                signatureBlockCompleteTable.addCell(logocell);
                PdfPCell incell = new PdfPCell(signatureTextTable);
                incell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(incell);
                PdfPCell commentcell = new PdfPCell(
                        new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10))));
                PdfPCell notecell = new PdfPCell(
                        new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                //commentcell.setPaddingTop(10);
                //commentcell.setColspan(2);
                // commentcell.setBorderWidth(0f);
                if (!sigComment.equals("")) {
                    signatureBlockCompleteTable.addCell(notecell);
                    signatureBlockCompleteTable.addCell(commentcell);
                }
                float[] cells = { 70, cellsize[0] + cellsize[1] };
                signatureBlockCompleteTable.setTotalWidth(cells);
                System.err.println(
                        "signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm);
                signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT,
                        verticalPositionPT, content);
                System.err.println(
                        "signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm);
                signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20,
                        topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20);
                //                    //////
                //                    AcroFields af = reader.getAcroFields();
                //                    ArrayList names = af.getSignatureNames();
                //                    for (int k = 0; k < names.size(); ++k) {
                //                        String name = (String) names.get(k);
                //                        System.out.println("Signature name: " + name);
                //                        System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name));
                //                        System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
                //                        PdfPKCS7 pk = af.verifySignature(name);
                //                        X509Certificate tempsigner = pk.getSigningCertificate();
                //                        Calendar cal = pk.getSignDate();
                //                        Certificate pkc[] = pk.getCertificates();
                //                        java.util.ResourceBundle tempoid =
                //                                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID");
                //                        String tmpEgovOID = "";
                //
                //                        for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) {
                //                            String element = o.nextElement();
                //                            // System.out.println(element + ":" + oid.getString(element));
                //                            if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) {
                //                                if (!tmpEgovOID.equals("")) {
                //                                    tmpEgovOID += ", ";
                //                                }
                //                                tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")";
                //                            }
                //                        }
                //                        //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
                //                        System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString());
                //                        System.out.println("\tDatum: " + cal.getTime().toString());
                //                        System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString());
                //                        System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber());
                //                        if (!tmpEgovOID.equals("")) {
                //                            System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID);
                //                        }
                //                        System.out.println("\n");
                //                        System.out.println("\tDocument modified: " + !pk.verify());
                ////                Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
                ////                if (fails == null) {
                ////                    System.out.println("\tCertificates verified against the KeyStore");
                ////                } else {
                ////                    System.out.println("\tCertificate failed: " + fails[1]);
                ////                }
                //                    }
                //
                //                //////
            } else {
                signatureBlock = new Rectangle(0, 0, 0, 0); // fake definition
            }
            PdfSignatureAppearance sap = stp.getSignatureAppearance();
            //                sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null,
            //                        PdfSignatureAppearance.WINCER_SIGNED );
            sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null);
            sap.setReason(signReason);
            sap.setLocation(signLocation);
            //                if (signText) {
            //                    sap.setVisibleSignature(signatureBlock,
            //                            pages + 1, "PortableSigner");
            //                }
            if (finalize) {
                sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
            } else {
                sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
            }
            stp.close();

            /* MODIFY BY: Denis Torresan
            Main.setResult(
              java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"),
              false,
              "");
                */

        } catch (Exception e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage());

        }
    } catch (KeyStoreException kse) {

        /* MODIFY BY: Denis Torresan
         Main.setResult(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"),
            true, kse.getLocalizedMessage());
         */

        throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                .getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage());

    }
}

From source file:org.alfresco.extension.countersign.action.executer.PDFAddSignatureFieldActionExecuter.java

License:Open Source License

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef,
 * org.alfresco.service.cmr.repository.NodeRef)
 *//*from  w  w w  . j ava2s .c  o  m*/
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {

    NodeService ns = serviceRegistry.getNodeService();
    if (ns.exists(actionedUponNodeRef) == false) {
        // node doesn't exist - can't do anything
        return;
    }

    String fieldName = (String) ruleAction.getParameterValue(PARAM_FIELDNAME);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);

    JSONObject box;
    int page = -1;

    // parse out the position JSON
    JSONObject positionObj = null;

    try {
        positionObj = (JSONObject) parser.parse(position);
    } catch (ParseException e) {
        logger.error("Could not parse position JSON from Share");
        throw new AlfrescoRuntimeException("Could not parse position JSON from Share");
    }

    // get the page
    page = Integer.parseInt(String.valueOf(positionObj.get("page")));

    // get the box
    box = (JSONObject) positionObj.get("box");

    try {
        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());
        OutputStream cos = serviceRegistry.getContentService()
                .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream();

        PdfStamper stamp = new PdfStamper(reader, cos);

        // does a field with this name already exist?
        AcroFields allFields = stamp.getAcroFields();

        // if this doc is already signed, cannot add a new sig field without 
        if (allFields.getSignatureNames() != null && allFields.getSignatureNames().size() > 0) {
            throw new AlfrescoRuntimeException("This document has signatures applied, "
                    + "adding a new signature field would invalidate existing signatures");
        }

        // cant create duplicate field names
        if (allFields.getFieldType(fieldName) == AcroFields.FIELD_TYPE_SIGNATURE) {
            throw new AlfrescoRuntimeException(
                    "A signature field named " + fieldName + " already exists in this document");
        }

        // create the signature field
        Rectangle pageRect = reader.getPageSizeWithRotation(page);
        Rectangle sigRect = positionBlock(pageRect, box);
        PdfFormField sigField = stamp.addSignature(fieldName, page, sigRect.getLeft(), sigRect.getBottom(),
                sigRect.getRight(), sigRect.getTop());

        // style the field (no borders)
        sigField.setBorder(new PdfBorderArray(0, 0, 0));
        sigField.setBorderStyle(new PdfBorderDictionary(0, PdfBorderDictionary.STYLE_SOLID));
        allFields.regenerateField(fieldName);

        // apply the change and close streams
        stamp.close();
        reader.close();
        cos.close();

        // once the signature field has been added, apply the sig field aspect
        if (!ns.hasAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE)) {
            ns.addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE, null);
        }

        // now update the signature fields metadata
        Serializable currentFields = ns.getProperty(actionedUponNodeRef,
                CounterSignSignatureModel.PROP_SIGNATUREFIELDS);
        ArrayList<String> fields = new ArrayList<String>();

        if (currentFields != null) {
            fields.addAll((List<String>) currentFields);
        }

        fields.add(fieldName);
        ns.setProperty(actionedUponNodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS, fields);
    } catch (IOException ioex) {
        throw new AlfrescoRuntimeException(ioex.getMessage());
    } catch (DocumentException dex) {
        throw new AlfrescoRuntimeException(dex.getMessage());
    }
}

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

/**
 * ??/*w  ww .  jav  a 2s . c o m*/
 *
 * @param srcPdf         ?
 * @param destPdf        
 * @param waterMarkText  ?
 * @param waterMarkImage ?
 */
public static void addWaterMarkFile(File srcPdf, File destPdf, String waterMarkText, File waterMarkImage)
        throws IOException, DocumentException {

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

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

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

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

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

    PdfReader reader = getPdfReader(srcPdf);

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

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

    // stamp.setMoreInfo(moreInfo);

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

    }

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

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

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

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

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

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

}