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:com.servoy.extensions.plugins.pdf_output.PDFPrinterJob.java
License:Open Source License
private Rectangle pageSize(PageFormat pf) { return new Rectangle(0, 0, d2f(pf.getWidth()), d2f(pf.getHeight())); }
From source file:corner.orm.tapestry.jasper.exporter.CornerPdfExporter.java
License:Apache License
/** * ?.????./*from w w w . ja v a 2 s. co m*/ * <p>:ColumnText?, * ?NO_MORE_COLUMN???,TextField??. * TextField?. * @see net.sf.jasperreports.engine.export.JRPdfExporter#exportText(net.sf.jasperreports.engine.JRPrintText) */ @Override protected void exportText(JRPrintText text) throws DocumentException { JRStyledText styledText = getStyledText(text, false); if (styledText == null) { return; } int textLength = styledText.length(); int x = text.getX() + getOffsetX(); int y = text.getY() + getOffsetY(); int width = text.getWidth(); int height = text.getHeight(); int topPadding = text.getTopPadding(); int leftPadding = text.getLeftPadding(); int bottomPadding = text.getBottomPadding(); int rightPadding = text.getRightPadding(); int xFillCorrection = 0; int yFillCorrection = 0; double angle = 0; switch (text.getRotation()) { case JRTextElement.ROTATION_LEFT: { y = text.getY() + getOffsetY() + text.getHeight(); xFillCorrection = 1; width = text.getHeight(); height = text.getWidth(); int tmpPadding = topPadding; topPadding = leftPadding; leftPadding = bottomPadding; bottomPadding = rightPadding; rightPadding = tmpPadding; angle = Math.PI / 2; break; } case JRTextElement.ROTATION_RIGHT: { x = text.getX() + getOffsetX() + text.getWidth(); yFillCorrection = -1; width = text.getHeight(); height = text.getWidth(); int tmpPadding = topPadding; topPadding = rightPadding; rightPadding = bottomPadding; bottomPadding = leftPadding; leftPadding = tmpPadding; angle = -Math.PI / 2; break; } case JRTextElement.ROTATION_UPSIDE_DOWN: { x = text.getX() + getOffsetX() + text.getWidth(); y = text.getY() + getOffsetY() + text.getHeight(); int tmpPadding = topPadding; topPadding = bottomPadding; bottomPadding = tmpPadding; tmpPadding = leftPadding; leftPadding = rightPadding; rightPadding = tmpPadding; angle = Math.PI; break; } case JRTextElement.ROTATION_NONE: default: { } } AffineTransform atrans = new AffineTransform(); atrans.rotate(angle, x, jasperPrint.getPageHeight() - y); pdfContentByte.transform(atrans); if (text.getMode() == JRElement.MODE_OPAQUE) { Color backcolor = text.getBackcolor(); pdfContentByte.setRGBColorStroke(backcolor.getRed(), backcolor.getGreen(), backcolor.getBlue()); pdfContentByte.setRGBColorFill(backcolor.getRed(), backcolor.getGreen(), backcolor.getBlue()); pdfContentByte.setLineWidth(1f); pdfContentByte.setLineDash(0f); pdfContentByte.rectangle(x + xFillCorrection, jasperPrint.getPageHeight() - y + yFillCorrection, width - 1, -height + 1); pdfContentByte.fillStroke(); } else { /* * pdfContentByte.setRGBColorStroke( text.getForecolor().getRed(), * text.getForecolor().getGreen(), text.getForecolor().getBlue() ); * pdfContentByte.setLineWidth(0.1f); * pdfContentByte.setLineDash(0f); pdfContentByte.rectangle( * text.getX() + offsetX, jasperPrint.getPageHeight() - text.getY() - * offsetY, text.getWidth(), - text.getHeight() ); * pdfContentByte.stroke(); */ } if (textLength > 0) { int horizontalAlignment = Element.ALIGN_LEFT; switch (text.getHorizontalAlignment()) { case JRAlignment.HORIZONTAL_ALIGN_LEFT: { if (text.getRunDirection() == JRPrintText.RUN_DIRECTION_LTR) { horizontalAlignment = Element.ALIGN_LEFT; } else { horizontalAlignment = Element.ALIGN_RIGHT; } break; } case JRAlignment.HORIZONTAL_ALIGN_CENTER: { horizontalAlignment = Element.ALIGN_CENTER; break; } case JRAlignment.HORIZONTAL_ALIGN_RIGHT: { if (text.getRunDirection() == JRPrintText.RUN_DIRECTION_LTR) { horizontalAlignment = Element.ALIGN_RIGHT; } else { horizontalAlignment = Element.ALIGN_LEFT; } break; } case JRAlignment.HORIZONTAL_ALIGN_JUSTIFIED: { horizontalAlignment = Element.ALIGN_JUSTIFIED; break; } default: { horizontalAlignment = Element.ALIGN_LEFT; } } float verticalOffset = 0f; switch (text.getVerticalAlignment()) { case JRAlignment.VERTICAL_ALIGN_TOP: { verticalOffset = 0f; break; } case JRAlignment.VERTICAL_ALIGN_MIDDLE: { verticalOffset = (height - topPadding - bottomPadding - text.getTextHeight()) / 2f; break; } case JRAlignment.VERTICAL_ALIGN_BOTTOM: { verticalOffset = height - topPadding - bottomPadding - text.getTextHeight(); break; } default: { verticalOffset = 0f; } } float llx = x + leftPadding; float lly = jasperPrint.getPageHeight() - y - topPadding - verticalOffset - text.getLeadingOffset(); float urx = x + width - rightPadding; float ury = jasperPrint.getPageHeight() - y - height + bottomPadding; //?,??? if (this.jasperMoveXY != null) { llx = x + leftPadding + jasperMoveXY.getX(); lly = jasperPrint.getPageHeight() - y - topPadding - verticalOffset - text.getLeadingOffset() - jasperMoveXY.getY(); urx = x + width - rightPadding + jasperMoveXY.getX(); ury = jasperPrint.getPageHeight() - y - height + bottomPadding - jasperMoveXY.getY(); } boolean isOver = false; int status = ColumnText.START_COLUMN; Phrase phrase = getPhrase(styledText, text); ColumnText colText = new ColumnText(pdfContentByte); colText.setSimpleColumn(phrase, llx, lly, urx, ury, 0, // text.getLineSpacingFactor(),// // * // text.getFont().getSize(), horizontalAlignment); colText.setLeading(0, text.getLineSpacingFactor());// * // text.getFont().getSize()); colText.setRunDirection( text.getRunDirection() == JRPrintText.RUN_DIRECTION_LTR ? PdfWriter.RUN_DIRECTION_LTR : PdfWriter.RUN_DIRECTION_RTL); float yLine = colText.getYLine(); // ColumnText while (colText.hasMoreText(status)) { status = colText.go(true); colText.setYLine(yLine); // ??,true if (status == ColumnText.NO_MORE_COLUMN) { isOver = true; break; } } // ,ColumnText if (!isOver) { colText.setText(phrase); status = ColumnText.START_COLUMN; while (colText.hasMoreText(status)) { status = colText.go(); colText.setYLine(yLine); } } else { // TextField,?? String key = text.getKey();// PdfTextid if (alreadyExistFields.contains(key)) { // ? key = createUniqueName(); } alreadyExistFields.add(key); TextField tf = new TextField(pdfContentByte.getPdfWriter(), new Rectangle(llx, lly, urx, ury), key); tf.setAlignment(horizontalAlignment); tf.setText(text.getText()); tf.setFont(PdfUtils.createSongLightBaseFont()); // styledText ??,? if (!text.isStyledText()) { tf.setOptions(TextField.MULTILINE); } try { pdfContentByte.getPdfWriter().addAnnotation(tf.getTextField()); } catch (IOException e) { e.printStackTrace(); } } } atrans = new AffineTransform(); atrans.rotate(-angle, x, jasperPrint.getPageHeight() - y); pdfContentByte.transform(atrans); /* */ exportBox(text, text); }
From source file:corner.orm.tapestry.pdf.components.PdfText.java
License:Apache License
/** * @see corner.orm.tapestry.pdf.components.AbstractPdfComponent#renderPdf(corner.orm.tapestry.pdf.PdfWriterDelegate, com.lowagie.text.Document) *///from w w w .ja va 2 s . c o m @Override public void renderPdf(PdfWriterDelegate writer, Document doc) { Defense.notNull(getRectangle(), "TextField?"); String[] p = getRectangle().split(","); Rectangle r = new Rectangle(Float.valueOf(p[0]), Float.valueOf(p[1]), Float.valueOf(p[2]), Float.valueOf(p[3])); TextField tf = getFieldCreator().createTextField(writer.getPdfWriter(), r, this.getId()); tf.setOptions(TextField.READ_ONLY); if (isMultiline()) { tf.setOptions(TextField.MULTILINE); } if (isAlignCenter()) { tf.setAlignment(Element.ALIGN_CENTER); } if (getValue() != null) {// tf.setFont(PdfUtils.createSongLightBaseFont()); if (getFontSize() > 0) tf.setFontSize(getFontSize()); tf.setText(getValue()); } try { writer.getPdfWriter().addAnnotation(tf.getTextField()); } catch (IOException e) { throw new PdfSystemException(e); } catch (DocumentException e) { throw new PdfSystemException(e); } }
From source file:corner.orm.tapestry.pdf.PdfBlock.java
License:Apache License
/** * ??/*from w w w . java2 s . com*/ * @param fieldPositions */ public void setPosition(float[] fieldPositions) { pageNum = (int) fieldPositions[0]; rectangle = new Rectangle(fieldPositions[1], fieldPositions[2], fieldPositions[3], fieldPositions[4]); }
From source file:de.dhbw.humbuch.util.PDFHandler.java
/** * Creates the pdf with the information in the object that was passed to the * constructor previously./*from w w w. j a v a2 s .c o m*/ * * @param path * where the file will be saved */ public void savePDF(String path) { try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path)); event = new HeaderFooter(); writer.setBoxSize("art", new Rectangle(36, 54, 559, 788)); writer.setPageEvent(event); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } this.document.open(); this.addMetaData(document); this.insertDocumentParts(document); this.document.close(); }
From source file:de.dhbw.humbuch.util.PDFHandler.java
/** * Creates a ByteArrayOutputStream which contains the PDF as a byte array. * /* w ww. java 2 s .c o m*/ * @return the byteArrayOutputStream the PDF is stored in, null if an error * occurred. */ public ByteArrayOutputStream createByteArrayOutputStreamForPDF() { ByteArrayOutputStream byteArrayOutputStream; try { byteArrayOutputStream = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream); event = new HeaderFooter(); writer.setBoxSize("art", new Rectangle(36, 54, 559, 788)); writer.setPageEvent(event); this.document.open(); this.addMetaData(document); int initialDocumentSize = writer.getCurrentDocumentSize(); this.insertDocumentParts(document); if (byteArrayOutputStream.size() > 0 || writer.getCurrentDocumentSize() > initialDocumentSize) { this.document.close(); } else { return null; } return byteArrayOutputStream; } catch (DocumentException e) { System.err.println("Could not create ByteArrayOutputStream of PDF data. " + e.getMessage()); } return null; }
From source file:de.thorstenberger.examServer.pdf.signature.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 w w w . ja v a 2s .c o 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 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:ec.gov.informatica.firmadigital.FirmaDigital.java
License:Open Source License
/** * Firma un archivo./* w w w .j a v a2 s.co m*/ * * @param data * @return */ // public void firmar(String claveToken, // String tipoCertificado, String urlCertificado, String path) { public void firmar(String claveToken, String tipoCertificado, String path) { try { KeyStore keyStore = null; Enumeration<String> enumeration = null; String alias = null; PrivateKey privateKey = null; Certificate[] certs = null; CMSSignatureProcessor cms = null; KeyStoreProvider keyStoreProvider = null; try { if (tipoCertificado.equals("1") || tipoCertificado.equals("2") || tipoCertificado.equals("3")) { System.out.println("- Firmando con certificado token." + tipoCertificado); keyStoreProvider = this.getKeyStoreProvider(tipoCertificado); System.out.println(claveToken.toCharArray()); keyStore = keyStoreProvider.getKeystore(claveToken.toCharArray()); enumeration = keyStore.aliases(); alias = enumeration.nextElement(); privateKey = (PrivateKey) keyStore.getKey(alias, null); cms = new BouncyCastleSignatureProcessor(keyStore); } // if (tipoCertificado.equals("4")) { // System.out.println("- Firmando con certificado en archivo."); // keyStore = java.security.KeyStore.getInstance("PKCS12"); // // instancia el ks // keyStore.load(new java.io.FileInputStream(urlCertificado), // claveToken.toCharArray()); // Enumeration en = keyStore.aliases(); // alias = ""; // Vector vectaliases = new Vector(); // while (en.hasMoreElements()) { // vectaliases.add(en.nextElement()); // } // String[] aliases = (String[]) (vectaliases.toArray(new // String[0])); // for (int i = 0; i < aliases.length; i++) { // if (keyStore.isKeyEntry(aliases[i])) { // alias = aliases[i]; // break; // } // } // privateKey = (PrivateKey) keyStore.getKey(alias, // claveToken.toCharArray()); // cms = new BouncyCastleSignatureProcessor(keyStore); // } } catch (Exception e) { System.out.println(" \n Fallo trayendo keystore " + e.getMessage()); } certs = keyStore.getCertificateChain(alias); Certificate[] chain = keyStore.getCertificateChain(alias); PrivateKey key = (PrivateKey) keyStore.getKey(alias, claveToken.toCharArray()); String revocados = ""; // para verificar revocados revocados = verificaRevocados(((X509Certificate) certs[0]).getSerialNumber().toString(), tipoCertificado); if (!revocados.isEmpty()) { System.out.println(" CERTIFICADO REVOCADO " + revocados); return; } System.out.println("- Certificado valido "); PdfReader reader = new PdfReader(path); FileOutputStream fout = new FileOutputStream(path + ".Firmado.pdf"); PdfStamper stp = PdfStamper.createSignature(reader, fout, '?'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason("Firma Procesos Legales"); sap.setLocation("RedTools"); // Aade la firma visible. Podemos comentarla para que no sea // visible. sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null); stp.close(); // byte[] datosFirmados = cms.sign(data, privateKey, certs); System.out.println("Firmado Correctamente..!"); // this.datosUsuarioActual = this // .crearDatosUsuario((X509Certificate) certs[0]); // llena la // clase de // tipo // datosUsuario // con el // certificado // actual // return datosFirmados; } catch (GeneralSecurityException e) { throw new RuntimeException(e); // FIXME } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } }
From source file:es.gob.afirma.signers.pades.PAdESSigner.java
License:Open Source License
/** Devuelve la posición de la página en donde debe agregarse * la firma. La medida de posicionamiento es el píxel y se cuenta en * el eje horizontal de izquierda a derecha y en el vertical de abajo a * arriba. *//*www. j av a 2s .c o m*/ private static Rectangle getSignaturePositionOnPage(final Properties extraParams) { if (extraParams.getProperty("signaturePositionOnPageLowerLeftX") != null && //$NON-NLS-1$ extraParams.getProperty("signaturePositionOnPageLowerLeftY") != null && //$NON-NLS-1$ extraParams.getProperty("signaturePositionOnPageUpperRightX") != null && //$NON-NLS-1$ extraParams.getProperty("signaturePositionOnPageUpperRightY") != null //$NON-NLS-1$ ) { try { return new Rectangle(Integer.parseInt(extraParams.getProperty("signaturePositionOnPageLowerLeftX")), //$NON-NLS-1$ Integer.parseInt(extraParams.getProperty("signaturePositionOnPageLowerLeftY")), //$NON-NLS-1$ Integer.parseInt(extraParams.getProperty("signaturePositionOnPageUpperRightX")), //$NON-NLS-1$ Integer.parseInt(extraParams.getProperty("signaturePositionOnPageUpperRightY")) //$NON-NLS-1$ ); } catch (final Exception e) { LOGGER.severe("Se ha indicado una posicion de firma invalida: " + e); //$NON-NLS-1$ } } return null; }
From source file:es.gob.afirma.signers.pades.PdfPreProcessor.java
License:Open Source License
/** Devuelve la posición de la página en donde debe agregarse el elemento * gráfico indicado como prefijo. La medida de posicionamiento es el píxel y se cuenta en * el eje horizontal de izquierda a derecha y en el vertical de abajo a arriba. * @param extraParams Definición de las coordenadas como conjunto de propiedades * @param prefix Prefijo de las propiedades de coordenada en el conjunto * @return Rectángulo que define una posición de un elemento en una página del PDF */ static Rectangle getPositionOnPage(final Properties extraParams, final String prefix) { if (extraParams == null || prefix == null) { LOGGER.severe("Se ha pedido una posicion para un elemento grafico nulo"); //$NON-NLS-1$ return null; }/*from w w w . j av a2s .co m*/ if (extraParams.getProperty(prefix + "PositionOnPageLowerLeftX") != null && //$NON-NLS-1$ extraParams.getProperty(prefix + "PositionOnPageLowerLeftY") != null && //$NON-NLS-1$ extraParams.getProperty(prefix + "PositionOnPageUpperRightX") != null && //$NON-NLS-1$ extraParams.getProperty(prefix + "PositionOnPageUpperRightY") != null //$NON-NLS-1$ ) { try { return new Rectangle(Integer.parseInt(extraParams.getProperty(prefix + "PositionOnPageLowerLeftX")), //$NON-NLS-1$ Integer.parseInt(extraParams.getProperty(prefix + "PositionOnPageLowerLeftY")), //$NON-NLS-1$ Integer.parseInt(extraParams.getProperty(prefix + "PositionOnPageUpperRightX")), //$NON-NLS-1$ Integer.parseInt(extraParams.getProperty(prefix + "PositionOnPageUpperRightY")) //$NON-NLS-1$ ); } catch (final Exception e) { LOGGER.severe( "Se ha indicado una posicion invalida para el elemento grafico '" + prefix + "': " + e); //$NON-NLS-1$ //$NON-NLS-2$ } } return null; }