Example usage for com.lowagie.text Rectangle getTop

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

Introduction

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

Prototype

public float getTop(float margin) 

Source Link

Document

Returns the upper right y-coordinate, considering a given margin.

Usage

From source file:SignPdf.java

License:Open Source License

/**
* Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this
* pdf had the current content at the current point in time.
*
* @param originalPdf//from   ww  w. j a  v a2s. c om
* @param targetPdf
* @param pk
* @param certChain
* @param revoked
* @param tsaAddress
* address of a rfc 3161 compatible timestamp server
* @param reason
* reason for the signature
* @param location
* location of signing
* @param contact
* emailaddress of the person who is signing
* @throws IOException
* @throws DocumentException
* @throws SignatureException
*/
public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf,
        final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress,
        final String reason, final String location, final String contact)
        throws IOException, DocumentException, SignatureException {
    // only an estimate, depends on the certificates returned by the TSA
    final int timestampSize = 4400;
    Security.addProvider(new BouncyCastleProvider());

    final PdfReader reader = new PdfReader(originalPdf);
    final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0');
    final PdfSignatureAppearance sap = stamper.getSignatureAppearance();

    // comment next lines to have an invisible signature
    Rectangle cropBox = reader.getCropBox(1);
    float width = 50;
    float height = 50;
    Rectangle rectangle = new Rectangle(cropBox.getRight(width) - 20, cropBox.getTop(height) - 20,
            cropBox.getRight() - 20, cropBox.getTop() - 20);
    sap.setVisibleSignature(rectangle, 1, null);
    //sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null);
    sap.setLayer2Text("");

    final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC");
    final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>();

    // some informational fields
    sig.setReason(reason);
    sig.setLocation(location);
    sig.setContact(contact);
    sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN"));
    sig.setDate(new PdfDate(Calendar.getInstance()));

    // signing stuff
    final byte[] digest = new byte[256];
    final byte[] rsaData = new byte[20];
    sig.setExternalDigest(digest, rsaData, "RSA");
    sig.setSignInfo(pk, certChain, revoked);
    final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS);
    // *2 to get hex size, +2 for delimiters
    PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2);
    exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength()));
    sig.put(PdfName.CONTENTS, contentsLit);

    // certification; will display dialog or blue bar in Acrobat Reader

    sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

    // process all the information set above
    sap.setCryptoDictionary(sig);
    sap.preClose(exclusionSizes);

    // calculate digest (hash)
    try {
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        final byte[] buf = new byte[8192];
        int n;
        final InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) != -1) {
            messageDigest.update(buf, 0, n);
        }
        final byte[] hash = messageDigest.digest();

        // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA)
        final Signature sign = Signature.getInstance("SHA1withRSA");
        sign.initSign(pk);
        sign.update(hash);
        final byte[] signature = sign.sign();

        // prepare the location of the signature in the target PDF
        contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS);
        final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2];
        final PdfPKCS7 pkcs7 = sig.getSigner();
        pkcs7.setExternalDigest(signature, hash, "RSA");
        final PdfDictionary dic = new PdfDictionary();

        byte[] ssig = pkcs7.getEncodedPKCS7();
        try {
            // try to retrieve cryptographic timestamp from configured tsa server
            ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null);
        } catch (final RuntimeException e) {
            log.error("Could not retrieve timestamp from server.", e);
        }
        System.arraycopy(ssig, 0, outc, 0, ssig.length);

        // add the timestamped signature
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));

        // finish up
        sap.close(dic);
    } catch (final InvalidKeyException e) {
        throw new RuntimeException("Internal implementation error! No such signature type.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new RuntimeException("Internal implementation error! No such algorithm type.", e);
    }
}

From source file:at.reppeitsolutions.formbuilder.components.pdf.itext.ITextRadio.java

License:Open Source License

public static Rectangle getBoxRectangle(Rectangle rectangle, int i) {
    Rectangle rect = new Rectangle(160, rectangle.getTop(i * 20), 180, rectangle.getTop(20 + i * 20));
    return rect;/*from   w w  w .  j a  va 2  s .  c om*/
}

From source file:at.reppeitsolutions.formbuilder.components.pdf.itext.ITextRadio.java

License:Open Source License

public static void addBoxDescription(Rectangle rectangle, int i, String[] values, PdfContentByte[] canvases) {
    Font f = new Font();
    f.setSize(ITextInputText.FONTSIZE);/* ww  w.  j  a va 2s . c  om*/
    ColumnText.showTextAligned(canvases[0], Element.ALIGN_LEFT, new Phrase(values[i], f), 190,
            rectangle.getTop(i * 20) - 15, 0);
}

From source file:classroom.filmfestival_c.Movies19.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    // step 1/*from   w  ww.j  a  va  2 s  . c o m*/
    Rectangle rect = PageSize.A4.rotate();
    Document document = new Document(rect);
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        Rectangle art = new Rectangle(rect.getLeft(36), rect.getBottom(36), rect.getRight(36), rect.getTop(36));
        writer.setBoxSize("art", art);
        // step 3
        document.open();
        // step 4

        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery(
                "select distinct festival.id.day from FestivalScreening as festival order by festival.id.day");
        java.util.List<Date> days = q.list();

        for (Date day : days) {
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(day);
            if (gc.get(GregorianCalendar.YEAR) != YEAR)
                continue;
            createSheet(session, day, writer);
            document.newPage();
        }
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_c.Movies20.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    // step 1//  w ww .j  ava2s. c o  m
    Rectangle rect = PageSize.A4.rotate();
    Document document = new Document(rect);
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        Rectangle art = new Rectangle(rect.getLeft(36), rect.getBottom(36), rect.getRight(36), rect.getTop(36));
        writer.setBoxSize("art", art);
        writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        // step 3
        document.open();
        // step 4

        PdfOutline root = writer.getDirectContent().getRootOutline();

        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery(
                "select distinct festival.id.day from FestivalScreening as festival order by festival.id.day");
        java.util.List<Date> days = q.list();

        for (Date day : days) {
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(day);
            if (gc.get(GregorianCalendar.YEAR) != YEAR)
                continue;
            createSheet(session, day, writer);
            new PdfOutline(root, new PdfDestination(PdfDestination.FIT), day.toString());
            document.newPage();
        }
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

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

License:Open Source License

/**
 * This method is for setting the properties of watermark Text.
 *///from w  ww  .j a  v  a  2s  . co  m
private void decoratePdfWatermarkText(PdfContentByte pdfContentByte, Rectangle rectangle,
        WatermarkBean watermarkBean) {
    float x, y, x1, y1, angle;
    final float OPACITY = 0.3f;
    PdfGState pdfGState = new PdfGState();
    pdfGState.setFillOpacity(OPACITY);
    int pageWidth = (int) rectangle.getWidth();
    int pageHeight = (int) rectangle.getHeight();
    try {
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) {
            pdfContentByte.beginText();
            pdfContentByte.setGState(pdfGState);
            Color fillColor = watermarkBean.getFont().getColor() == null
                    ? WatermarkConstants.DEFAULT_WATERMARK_COLOR
                    : watermarkBean.getFont().getColor();
            pdfContentByte.setColorFill(fillColor);

            if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_FOOTER)) {

                pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                        watermarkBean.getPositionFont().getSize());
                if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(),
                            (rectangle.getLeft(rectangle.getBorderWidthLeft())
                                    + rectangle.getRight(rectangle.getBorderWidthRight())) / 2,
                            rectangle.getBottom(rectangle.getBorderWidthBottom()
                                    + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(),
                            rectangle.getRight(rectangle.getBorderWidthRight()),
                            rectangle.getBottom(rectangle.getBorderWidthBottom()
                                    + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(),
                            rectangle.getLeft(rectangle.getBorderWidthLeft()),
                            rectangle.getBottom(rectangle.getBorderWidthBottom()
                                    + watermarkBean.getPositionFont().getSize()),
                            0);
                }
            } else if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_HEADER)) {
                pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                        watermarkBean.getPositionFont().getSize());
                if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(),
                            (rectangle.getLeft(rectangle.getBorderWidthLeft())
                                    + rectangle.getRight(rectangle.getBorderWidthRight())) / 2,
                            rectangle.getTop(
                                    rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(),
                            rectangle.getRight(rectangle.getBorderWidthRight()),
                            rectangle.getTop(
                                    rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()),
                            0);
                } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) {
                    pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(),
                            rectangle.getLeft(rectangle.getBorderWidthLeft()),
                            rectangle.getTop(
                                    rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()),
                            0);
                }
            } else {
                pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(),
                        watermarkBean.getFont().getSize());
                int textWidth = (int) pdfContentByte.getEffectiveStringWidth(watermarkBean.getText(), false);
                int diagonal = (int) Math.sqrt((pageWidth * pageWidth) + (pageHeight * pageHeight));
                int pivotPoint = (diagonal - textWidth) / 2;

                angle = (float) Math.atan((float) pageHeight / pageWidth);

                x = (float) (pivotPoint * pageWidth) / diagonal;
                y = (float) (pivotPoint * pageHeight) / diagonal;

                x1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.sin(angle));
                y1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.cos(angle));

                pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(), x + x1, y - y1,
                        (float) Math.toDegrees(angle));
            }
            pdfContentByte.endText();
        }
    } catch (Exception exception) {
        LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + exception.getMessage());
    }

}

From source file:questions.forms.FormWithTooltips.java

/**
 * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell,
 *      com.lowagie.text.Rectangle, com.lowagie.text.pdf.PdfContentByte[])
 *//*from   w w w . ja  v  a  2s .co m*/
public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb) {
    kid.setWidget(new Rectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding),
            rect.getTop(padding)), PdfAnnotation.HIGHLIGHT_INVERT);
    kid.setUserName(tooltip);
    try {
        parent.addKid(kid);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:questions.forms.KidsOnDifferentPages.java

public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb) {
    kid.setWidget(new Rectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding),
            rect.getTop(padding)), PdfAnnotation.HIGHLIGHT_INVERT);
}

From source file:questions.stamppages.BookmarksToTOC1.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*ww  w.ja v  a  2 s  .co  m*/
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        writer.setPageEvent(new ParagraphBookmarkEvents(false));
        document.open();
        BufferedReader reader = new BufferedReader(new FileReader(RESOURCE));
        String line;
        Paragraph p;
        while ((line = reader.readLine()) != null) {
            p = new Paragraph(line);
            p.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(p);
            document.add(Chunk.NEWLINE);
        }
        reader.close();
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    try {
        PdfReader reader = new PdfReader(baos.toByteArray());
        Rectangle rect = reader.getPageSizeWithRotation(1);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        stamper.insertPage(1, rect);
        ColumnText column = new ColumnText(stamper.getOverContent(1));
        column.setSimpleColumn(rect.getLeft(36), rect.getBottom(36), rect.getRight(36), rect.getTop(36));
        column.addElement(new Paragraph("TABLE OF CONTENTS"));
        List<Map> list = SimpleBookmark.getBookmark(reader);
        Chunk link;
        PdfAction action;
        String info;
        int p = 1;
        float y = 10;
        for (Map<String, String> bookmark : list) {
            link = new Chunk(bookmark.get("Title"));
            info = bookmark.get("Page");
            p = Integer.parseInt(info.substring(0, info.indexOf(' ')));
            y = Float.parseFloat(info.substring(info.lastIndexOf(' ') + 1) + "f");
            action = PdfAction.gotoLocalPage(p, new PdfDestination(PdfDestination.FITH, y),
                    stamper.getWriter());
            link.setAction(action);
            column.addElement(new Paragraph(link));
        }
        column.go();
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:questions.stamppages.BookmarksToTOC2.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//  w w w  .j  a  v  a 2s.c o  m
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        writer.setPageEvent(new ParagraphBookmarkEvents(true));
        document.open();
        BufferedReader reader = new BufferedReader(new FileReader(RESOURCE));
        String line;
        Paragraph p;
        while ((line = reader.readLine()) != null) {
            p = new Paragraph(line);
            p.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(p);
            document.add(Chunk.NEWLINE);
        }
        reader.close();
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    try {
        PdfReader reader = new PdfReader(baos.toByteArray());
        Rectangle rect = reader.getPageSizeWithRotation(1);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        stamper.insertPage(1, rect);
        ColumnText column = new ColumnText(stamper.getOverContent(1));
        column.setSimpleColumn(rect.getLeft(36), rect.getBottom(36), rect.getRight(36), rect.getTop(36));
        column.addElement(new Paragraph("TABLE OF CONTENTS"));
        List<Map> list = SimpleBookmark.getBookmark(reader);
        Chunk link;
        String dest;
        for (Map<String, String> bookmark : list) {
            link = new Chunk(bookmark.get("Title"));
            dest = bookmark.get("Named");
            link.setAction(PdfAction.gotoLocalPage(dest, false));
            column.addElement(new Paragraph(link));
        }
        column.go();
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}