KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lowagie > text > pdf > RadioCheckField


1 /*
2  * Copyright 2005 by Paulo Soares.
3  *
4  * The contents of this file are subject to the Mozilla Public License Version 1.1
5  * (the "License"); you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
7  *
8  * Software distributed under the License is distributed on an "AS IS" basis,
9  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10  * for the specific language governing rights and limitations under the License.
11  *
12  * The Original Code is 'iText, a free JAVA-PDF library'.
13  *
14  * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
15  * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
16  * All Rights Reserved.
17  * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
18  * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
19  *
20  * Contributor(s): all the names of the contributors are added in the source code
21  * where applicable.
22  *
23  * Alternatively, the contents of this file may be used under the terms of the
24  * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
25  * provisions of LGPL are applicable instead of those above. If you wish to
26  * allow use of your version of this file only under the terms of the LGPL
27  * License and not to allow others to use your version of this file under
28  * the MPL, indicate your decision by deleting the provisions above and
29  * replace them with the notice and other provisions required by the LGPL.
30  * If you do not delete the provisions above, a recipient may use your version
31  * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
32  *
33  * This library is free software; you can redistribute it and/or modify it
34  * under the terms of the MPL as stated above or under the terms of the GNU
35  * Library General Public License as published by the Free Software Foundation;
36  * either version 2 of the License, or any later version.
37  *
38  * This library is distributed in the hope that it will be useful, but WITHOUT
39  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
40  * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
41  * details.
42  *
43  * If you didn't download this code from the following link, you should check if
44  * you aren't using an obsolete version:
45  * http://www.lowagie.com/iText/
46  */

47 package com.lowagie.text.pdf;
48
49 import java.io.IOException JavaDoc;
50
51 import com.lowagie.text.DocumentException;
52 import com.lowagie.text.ExceptionConverter;
53 import com.lowagie.text.Rectangle;
54
55 /**
56  * Creates a radio or a check field.
57  * <p>
58  * Example usage:
59  * <p>
60  * <PRE>
61  * Document document = new Document(PageSize.A4, 50, 50, 50, 50);
62  * PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
63  * document.open();
64  * PdfContentByte cb = writer.getDirectContent();
65  * RadioCheckField bt = new RadioCheckField(writer, new Rectangle(100, 100, 200, 200), "radio", "v1");
66  * bt.setCheckType(RadioCheckField.TYPE_CIRCLE);
67  * bt.setBackgroundColor(Color.cyan);
68  * bt.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
69  * bt.setBorderColor(Color.red);
70  * bt.setTextColor(Color.yellow);
71  * bt.setBorderWidth(BaseField.BORDER_WIDTH_THICK);
72  * bt.setChecked(false);
73  * PdfFormField f1 = bt.getRadioField();
74  * bt.setOnValue("v2");
75  * bt.setChecked(true);
76  * bt.setBox(new Rectangle(100, 300, 200, 400));
77  * PdfFormField f2 = bt.getRadioField();
78  * bt.setChecked(false);
79  * PdfFormField top = bt.getRadioGroup(true, false);
80  * bt.setOnValue("v3");
81  * bt.setBox(new Rectangle(100, 500, 200, 600));
82  * PdfFormField f3 = bt.getRadioField();
83  * top.addKid(f1);
84  * top.addKid(f2);
85  * top.addKid(f3);
86  * writer.addAnnotation(top);
87  * bt = new RadioCheckField(writer, new Rectangle(300, 300, 400, 400), "check1", "Yes");
88  * bt.setCheckType(RadioCheckField.TYPE_CHECK);
89  * bt.setBorderWidth(BaseField.BORDER_WIDTH_THIN);
90  * bt.setBorderColor(Color.black);
91  * bt.setBackgroundColor(Color.white);
92  * PdfFormField ck = bt.getCheckField();
93  * writer.addAnnotation(ck);
94  * document.close();
95  * </PRE>
96  * @author Paulo Soares (psoares@consiste.pt)
97  */

98 public class RadioCheckField extends BaseField {
99
100     /** A field with the symbol check */
101     public static final int TYPE_CHECK = 1;
102     /** A field with the symbol circle */
103     public static final int TYPE_CIRCLE = 2;
104     /** A field with the symbol cross */
105     public static final int TYPE_CROSS = 3;
106     /** A field with the symbol diamond */
107     public static final int TYPE_DIAMOND = 4;
108     /** A field with the symbol square */
109     public static final int TYPE_SQUARE = 5;
110     /** A field with the symbol star */
111     public static final int TYPE_STAR = 6;
112     
113     private static String JavaDoc typeChars[] = {"4", "l", "8", "u", "n", "H"};
114     
115     /**
116      * Holds value of property checkType.
117      */

118     private int checkType;
119     
120     /**
121      * Holds value of property onValue.
122      */

123     private String JavaDoc onValue;
124     
125     /**
126      * Holds value of property checked.
127      */

128     private boolean checked;
129     
130     /**
131      * Creates a new instance of RadioCheckField
132      * @param writer the document <CODE>PdfWriter</CODE>
133      * @param box the field location and dimensions
134      * @param fieldName the field name. It must not be <CODE>null</CODE>
135      * @param onValue the value when the field is checked
136      */

137     public RadioCheckField(PdfWriter writer, Rectangle box, String JavaDoc fieldName, String JavaDoc onValue) {
138         super(writer, box, fieldName);
139         setOnValue(onValue);
140         setCheckType(TYPE_CIRCLE);
141     }
142     
143     /**
144      * Getter for property checkType.
145      * @return Value of property checkType.
146      */

147     public int getCheckType() {
148         return this.checkType;
149     }
150     
151     /**
152      * Sets the checked symbol. It can be
153      * <CODE>TYPE_CHECK</CODE>,
154      * <CODE>TYPE_CIRCLE</CODE>,
155      * <CODE>TYPE_CROSS</CODE>,
156      * <CODE>TYPE_DIAMOND</CODE>,
157      * <CODE>TYPE_SQUARE</CODE> and
158      * <CODE>TYPE_STAR</CODE>.
159      * @param checkType the checked symbol
160      */

161     public void setCheckType(int checkType) {
162         if (checkType < TYPE_CHECK || checkType > TYPE_STAR)
163             checkType = TYPE_CIRCLE;
164         this.checkType = checkType;
165         setText(typeChars[checkType - 1]);
166         try {
167             setFont(BaseFont.createFont(BaseFont.ZAPFDINGBATS, BaseFont.WINANSI, false));
168         }
169         catch (Exception JavaDoc e) {
170             throw new ExceptionConverter(e);
171         }
172     }
173     
174     /**
175      * Getter for property onValue.
176      * @return Value of property onValue.
177      */

178     public String JavaDoc getOnValue() {
179         return this.onValue;
180     }
181     
182     /**
183      * Sets the value when the field is checked.
184      * @param onValue the value when the field is checked
185      */

186     public void setOnValue(String JavaDoc onValue) {
187         this.onValue = onValue;
188     }
189     
190     /**
191      * Getter for property checked.
192      * @return Value of property checked.
193      */

194     public boolean isChecked() {
195         return this.checked;
196     }
197     
198     /**
199      * Sets the state of the field to checked or unchecked.
200      * @param checked the state of the field, <CODE>true</CODE> for checked
201      * and <CODE>false</CODE> for unchecked
202      */

203     public void setChecked(boolean checked) {
204         this.checked = checked;
205     }
206     
207     /**
208      * Gets the field appearance.
209      * @param isRadio <CODE>true</CODE> for a radio field and <CODE>false</CODE>
210      * for a check field
211      * @param on <CODE>true</CODE> for the checked state, <CODE>false</CODE>
212      * otherwise
213      * @throws IOException on error
214      * @throws DocumentException on error
215      * @return the appearance
216      */

217     public PdfAppearance getAppearance(boolean isRadio, boolean on) throws IOException JavaDoc, DocumentException {
218         if (isRadio && checkType == TYPE_CIRCLE)
219             return getAppearanceRadioCircle(on);
220         PdfAppearance app = getBorderAppearance();
221         if (!on)
222             return app;
223         BaseFont ufont = getRealFont();
224         boolean borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET;
225         float h = box.getHeight() - borderWidth * 2;
226         float bw2 = borderWidth;
227         if (borderExtra) {
228             h -= borderWidth * 2;
229             bw2 *= 2;
230         }
231         float offsetX = (borderExtra ? 2 * borderWidth : borderWidth);
232         offsetX = Math.max(offsetX, 1);
233         float offX = Math.min(bw2, offsetX);
234         float wt = box.getWidth() - 2 * offX;
235         float ht = box.getHeight() - 2 * offX;
236         float fsize = fontSize;
237         if (fsize == 0) {
238             float bw = ufont.getWidthPoint(text, 1);
239             if (bw == 0)
240                 fsize = 12;
241             else
242                 fsize = wt / bw;
243             float nfsize = h / (ufont.getFontDescriptor(BaseFont.ASCENT, 1));
244             fsize = Math.min(fsize, nfsize);
245         }
246         app.saveState();
247         app.rectangle(offX, offX, wt, ht);
248         app.clip();
249         app.newPath();
250         if (textColor == null)
251             app.resetGrayFill();
252         else
253             app.setColorFill(textColor);
254         app.beginText();
255         app.setFontAndSize(ufont, fsize);
256         app.setTextMatrix((box.getWidth() - ufont.getWidthPoint(text, fsize)) / 2,
257             (box.getHeight() - ufont.getAscentPoint(text, fsize)) / 2);
258         app.showText(text);
259         app.endText();
260         app.restoreState();
261         return app;
262     }
263
264     /**
265      * Gets the special field appearance for the radio circle.
266      * @param on <CODE>true</CODE> for the checked state, <CODE>false</CODE>
267      * otherwise
268      * @return the appearance
269      */

270     public PdfAppearance getAppearanceRadioCircle(boolean on) {
271         PdfAppearance app = PdfAppearance.createAppearance(writer, box.getWidth(), box.getHeight());
272         switch (rotation) {
273             case 90:
274                 app.setMatrix(0, 1, -1, 0, box.getHeight(), 0);
275                 break;
276             case 180:
277                 app.setMatrix(-1, 0, 0, -1, box.getWidth(), box.getHeight());
278                 break;
279             case 270:
280                 app.setMatrix(0, -1, 1, 0, 0, box.getWidth());
281                 break;
282         }
283         Rectangle box = new Rectangle(app.getBoundingBox());
284         float cx = box.getWidth() / 2;
285         float cy = box.getHeight() / 2;
286         float r = (Math.min(box.getWidth(), box.getHeight()) - borderWidth) / 2;
287         if (r <= 0)
288             return app;
289         if (backgroundColor != null) {
290             app.setColorFill(backgroundColor);
291             app.circle(cx, cy, r + borderWidth / 2);
292             app.fill();
293         }
294         if (borderWidth > 0 && borderColor != null) {
295             app.setLineWidth(borderWidth);
296             app.setColorStroke(borderColor);
297             app.circle(cx, cy, r);
298             app.stroke();
299         }
300         if (on) {
301             if (textColor == null)
302                 app.resetGrayFill();
303             else
304                 app.setColorFill(textColor);
305             app.circle(cx, cy, r / 2);
306             app.fill();
307         }
308         return app;
309     }
310     
311     /**
312      * Gets a radio group. It's composed of the field specific keys, without the widget
313      * ones. This field is to be used as a field aggregator with {@link PdfFormField#addKid(PdfFormField) addKid()}.
314      * @param noToggleToOff if <CODE>true</CODE>, exactly one radio button must be selected at all
315      * times; clicking the currently selected button has no effect.
316      * If <CODE>false</CODE>, clicking
317      * the selected button deselects it, leaving no button selected.
318      * @param radiosInUnison if <CODE>true</CODE>, a group of radio buttons within a radio button field that
319      * use the same value for the on state will turn on and off in unison; that is if
320      * one is checked, they are all checked. If <CODE>false</CODE>, the buttons are mutually exclusive
321      * (the same behavior as HTML radio buttons)
322      * @return the radio group
323      */

324     public PdfFormField getRadioGroup(boolean noToggleToOff, boolean radiosInUnison) {
325         PdfFormField field = PdfFormField.createRadioButton(writer, noToggleToOff);
326         if (radiosInUnison)
327             field.setFieldFlags(PdfFormField.FF_RADIOSINUNISON);
328         field.setFieldName(fieldName);
329         if ((options & READ_ONLY) != 0)
330             field.setFieldFlags(PdfFormField.FF_READ_ONLY);
331         if ((options & REQUIRED) != 0)
332             field.setFieldFlags(PdfFormField.FF_REQUIRED);
333         field.setValueAsName(checked ? onValue : "Off");
334         return field;
335     }
336     
337     /**
338      * Gets the radio field. It's only composed of the widget keys and must be used
339      * with {@link #getRadioGroup(boolean,boolean)}.
340      * @return the radio field
341      * @throws IOException on error
342      * @throws DocumentException on error
343      */

344     public PdfFormField getRadioField() throws IOException JavaDoc, DocumentException {
345         return getField(true);
346     }
347     
348     /**
349      * Gets the check field.
350      * @return the check field
351      * @throws IOException on error
352      * @throws DocumentException on error
353      */

354     public PdfFormField getCheckField() throws IOException JavaDoc, DocumentException {
355         return getField(false);
356     }
357     
358     /**
359      * Gets a radio or check field.
360      * @param isRadio <CODE>true</CODE> to get a radio field, <CODE>false</CODE> to get
361      * a check field
362      * @throws IOException on error
363      * @throws DocumentException on error
364      * @return the field
365      */

366     protected PdfFormField getField(boolean isRadio) throws IOException JavaDoc, DocumentException {
367         PdfFormField field = null;
368         if (isRadio)
369             field = PdfFormField.createEmpty(writer);
370         else
371             field = PdfFormField.createCheckBox(writer);
372         field.setWidget(box, PdfAnnotation.HIGHLIGHT_INVERT);
373         if (!isRadio) {
374             field.setFieldName(fieldName);
375             if ((options & READ_ONLY) != 0)
376                 field.setFieldFlags(PdfFormField.FF_READ_ONLY);
377             if ((options & REQUIRED) != 0)
378                 field.setFieldFlags(PdfFormField.FF_REQUIRED);
379             field.setValueAsName(checked ? onValue : "Off");
380         }
381         if (text != null)
382             field.setMKNormalCaption(text);
383         if (rotation != 0)
384             field.setMKRotation(rotation);
385         field.setBorderStyle(new PdfBorderDictionary(borderWidth, borderStyle, new PdfDashPattern(3)));
386         PdfAppearance tpon = getAppearance(isRadio, true);
387         PdfAppearance tpoff = getAppearance(isRadio, false);
388         field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, onValue, tpon);
389         field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", tpoff);
390         field.setAppearanceState(checked ? onValue : "Off");
391         PdfAppearance da = (PdfAppearance)tpon.getDuplicate();
392         da.setFontAndSize(getRealFont(), fontSize);
393         if (textColor == null)
394             da.setGrayFill(0);
395         else
396             da.setColorFill(textColor);
397         field.setDefaultAppearanceString(da);
398         if (borderColor != null)
399             field.setMKBorderColor(borderColor);
400         if (backgroundColor != null)
401             field.setMKBackgroundColor(backgroundColor);
402         switch (visibility) {
403             case HIDDEN:
404                 field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_HIDDEN);
405                 break;
406             case VISIBLE_BUT_DOES_NOT_PRINT:
407                 break;
408             case HIDDEN_BUT_PRINTABLE:
409                 field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_NOVIEW);
410                 break;
411             default:
412                 field.setFlags(PdfAnnotation.FLAGS_PRINT);
413                 break;
414         }
415         return field;
416     }
417 }
Popular Tags