List of usage examples for com.lowagie.text Rectangle Rectangle
public Rectangle(float llx, float lly, float urx, float ury)
Rectangle
-object. 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 www . j av a 2s . co m*/ * @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:androidGLUESigner.pdf.PDFSignerEngine.java
License:Open Source License
/** * Prepare the signing of the pdf (siganture appearance, placeholders, sigimage, ..) * @param inputStream the stream to the input pdf file * @param outputStream the stream to the output pdf file * @return hash value with ocsp included * @throws IOException/*w w w . j a v a 2s .co m*/ * @throws DocumentException * @throws GeneralSecurityException */ public byte[] prepareSign(InputStream inputStream, OutputStream outputStream) throws IOException, DocumentException, GeneralSecurityException { PdfReader reader = new PdfReader(inputStream); PdfStamper stp = PdfStamper.createSignature(reader, outputStream, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(null, getCertificateChain(), null, PdfSignatureAppearance.WINCER_SIGNED); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(siginfo.getSignatureReason()); dic.setLocation(siginfo.getSignatureLocation()); dic.setName(siginfo.getSignatureName()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); // get the selected rectangle and pagenumber for visible signature Rectangle signatureRect = new Rectangle(siginfo.getSignatureRect().left, siginfo.getSignatureRect().bottom, siginfo.getSignatureRect().right, siginfo.getSignatureRect().top); int pageNumber = siginfo.getPageNumber(); sap.setVisibleSignature(signatureRect, pageNumber, null); // set signature picture, if there is one if (siginfo.getSignatureType() == SignatureType.PICTURE) { Image obj_pic = Image.getInstance(siginfo.getImagePath()); sap.setImage(obj_pic); } // preserve some space for the contents HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(SIGNATURE_MAX_SIZE * 2 + 2)); sap.preClose(exc); // Save placeholder which will be replaced with actual signature later byte[] placeHolder = getPlaceHolderArr(SIGNATURE_MAX_SIZE * 2); // Replace the contents PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(placeHolder).setHexWriting(true)); sap.close(dic2); // Calculate the digest InputStream data = sap.getRangeStream(); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } hash = messageDigest.digest(); calendar = Calendar.getInstance(); ocsp = ocspRequest(cert, issuerCert); System.out.println("Got OCSP response, length = " + ocsp.length); // Calculate another digest over authenticatedAttributes PdfPKCS7 sgn = new PdfPKCS7(null, getCertificateChain(), null, hashAlgo, null, true); byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, calendar, ocsp); return sh; }
From source file:androidGLUESigner.pdf.PDFSignerEngine.java
License:Open Source License
/** * Simple Sign method to create a signature without Online Timestamp (needed if device * has no internet connection)//from ww w . jav a 2s .com * * @param inputfile the inputfile * @param outputfile the outpuftile * @param connection the IConnection Object */ public void simpleSign(String inputfile, String outputfile, IConnection connection) throws IOException, DocumentException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, ReaderException { try { SignatureInfo sigInfo = getSiginfo(); PdfReader reader = new PdfReader(inputfile); FileOutputStream fout = new FileOutputStream(outputfile); PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(null, new Certificate[] { getCertificateChain()[0] }, null, PdfSignatureAppearance.SELF_SIGNED); sap.setReason(sigInfo.getSignatureReason()); sap.setLocation(sigInfo.getSignatureLocation()); // get the selected rectangle and pagenumber for visible signature Rectangle signatureRect = new Rectangle(siginfo.getSignatureRect().left, siginfo.getSignatureRect().bottom, siginfo.getSignatureRect().right, siginfo.getSignatureRect().top); int pageNumber = siginfo.getPageNumber(); sap.setVisibleSignature(signatureRect, pageNumber, null); // set signature picture, if there is one if (siginfo.getSignatureType() == SignatureType.PICTURE) { Image obj_pic = Image.getInstance(siginfo.getImagePath()); sap.setImage(obj_pic); } sap.setExternalDigest(new byte[256], new byte[20], null); sap.preClose(); java.io.InputStream inp = sap.getRangeStream(); byte bytesToHash[] = IOUtils.toByteArray(inp); // sign the hash value byte[] signed = connection.sign(bytesToHash); PdfPKCS7 pdfSignature = sap.getSigStandard().getSigner(); pdfSignature.setExternalDigest(signed, null, "RSA"); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.CONTENTS, new PdfString(pdfSignature.getEncodedPKCS1()).setHexWriting(true)); sap.close(dic); } catch (Exception e) { Logger.toConsole(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 ava 2s . c om }
From source file:buckley.compile.FieldSizeFactory.java
License:Apache License
public Rectangle build(Field field) { float xOffset = field.getX() + field.getWidth(); return new Rectangle(field.getX(), field.getY(), xOffset, field.getY() + field.getHeight()); }
From source file:classroom.filmfestival_c.Movies19.java
@SuppressWarnings("unchecked") public static void main(String[] args) { // step 1//from w w w. j av a2 s . c om 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 w w . ja v a 2s. 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:classroom.newspaper_b.Newspaper08.java
public static void main(String[] args) { try {// w w w. j ava 2 s. co m PdfReader reader = new PdfReader(NEWSPAPER); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); PdfAnnotation annotation1 = PdfAnnotation.createText(stamper.getWriter(), new Rectangle(LLX1, LLY1, URX1, URY1), "Advertisement 1", MESSAGE, false, "Insert"); PdfAppearance ap = stamper.getOverContent(1).createAppearance(W1, H1); ap.setRGBColorStroke(0xFF, 0x00, 0x00); ap.setLineWidth(3); ap.moveTo(0, 0); ap.lineTo(W1, H1); ap.moveTo(W1, 0); ap.lineTo(0, H1); ap.stroke(); annotation1.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap); stamper.addAnnotation(annotation1, 1); PdfAnnotation annotation2 = PdfAnnotation.createText(stamper.getWriter(), new Rectangle(LLX2, LLY2, URX2, URY2), "Advertisement 2", MESSAGE, true, "Insert"); annotation2.put(PdfName.C, new PdfArray(new float[] { 0, 0, 1 })); stamper.addAnnotation(annotation2, 1); stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:classroom.newspaper_b.Newspaper09.java
public static void main(String[] args) { try {/*from w w w . java 2 s .c o m*/ PdfReader reader = new PdfReader(NEWSPAPER); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); PdfAnnotation annotation1 = PdfAnnotation.createSquareCircle(stamper.getWriter(), new Rectangle(LLX1, LLY1, URX1, URY1), MESSAGE, true); annotation1.put(PdfName.T, new PdfString("Advertisement 1")); annotation1.put(PdfName.C, new PdfArray(new float[] { 1, 0, 0 })); stamper.addAnnotation(annotation1, 1); PdfAnnotation annotation2 = PdfAnnotation.createText(stamper.getWriter(), new Rectangle(LLX2, LLY2, URX2, URY2), "Advertisement 2", MESSAGE, false, null); annotation2.put(PdfName.NM, new PdfString("ad2")); // the text must be read only, and the annotation set to NOVIEW annotation2.put(PdfName.F, new PdfNumber(PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_NOVIEW)); // we create a popup annotation that will define where the rectangle will appear PdfAnnotation popup = PdfAnnotation.createPopup(stamper.getWriter(), new Rectangle(LLX2 + 50, LLY2 + 120, URX2 - 80, URY2 - 120), null, false); // we add a reference to the text annotation to the popup annotation popup.put(PdfName.PARENT, annotation2.getIndirectReference()); // we add a reference to the popup annotation to the text annotation annotation2.put(PdfName.POPUP, popup.getIndirectReference()); // we add both annotations to the writer stamper.addAnnotation(annotation2, 1); stamper.addAnnotation(popup, 1); // the text annotation can't be viewed (it's invisible) // we create a widget annotation named mywidget (it's a button field) PushbuttonField field = new PushbuttonField(stamper.getWriter(), new Rectangle(LLX2, LLY2, URX2, URY2), "button"); PdfAnnotation widget = field.getField(); PdfDictionary dict = new PdfDictionary(); // we write some javascript that makes the popup of the text annotation visible/invisible on mouse enter/exit String js1 = "var t = this.getAnnot(this.pageNum, 'ad2'); t.popupOpen = true; var w = this.getField('button'); w.setFocus();"; PdfAction enter = PdfAction.javaScript(js1, stamper.getWriter()); dict.put(PdfName.E, enter); String js2 = "var t = this.getAnnot(this.pageNum, 'ad2'); t.popupOpen = false;"; PdfAction exit = PdfAction.javaScript(js2, stamper.getWriter()); dict.put(PdfName.X, exit); // we add the javascript as additional action widget.put(PdfName.AA, dict); // we add the button field stamper.addAnnotation(widget, 1); stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:classroom.newspaper_b.Newspaper10.java
public static void main(String[] args) { try {/* w w w .j av a2 s .c o m*/ PdfReader reader = new PdfReader(NEWSPAPER); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); PushbuttonField button; Rectangle rect; rect = new Rectangle(100, 980, 700, 1000); button = new PushbuttonField(stamper.getWriter(), rect, "click"); button.setBackgroundColor(Color.ORANGE); button.setText("Click here to close window"); button.setLayout(PushbuttonField.LAYOUT_LABEL_ONLY); button.setAlignment(Element.ALIGN_RIGHT); PdfFormField menubar = button.getField(); String js = "var f1 = getField('click'); f1.display = display.hidden;" + "var f2 = getField('advertisement'); f2.display = display.hidden;"; menubar.setAction(PdfAction.javaScript(js, stamper.getWriter())); stamper.addAnnotation(menubar, 1); rect = new Rectangle(100, 500, 700, 980); button = new PushbuttonField(stamper.getWriter(), rect, "advertisement"); button.setBackgroundColor(Color.WHITE); button.setBorderColor(Color.ORANGE); button.setImage(Image.getInstance(IMG)); button.setText("Buy the book iText in Action"); button.setLayout(PushbuttonField.LAYOUT_LABEL_TOP_ICON_BOTTOM); PdfFormField advertisement = button.getField(); advertisement.setAction(new PdfAction("http://www.1t3xt.com/docs/book.php")); stamper.addAnnotation(advertisement, 1); stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }