How can I add text to a Checkbox I create using iTextSharp? - checkbox

Derived from Jeff S's methodology found here, I can add a "Checkbox" to a PDF page like so:
PdfPTable tblFirstRow = new PdfPTable(5);
tblFirstRow.SpacingBefore = 4f;
tblFirstRow.HorizontalAlignment = Element.ALIGN_LEFT;
. . . // code where textboxes are added has been elided for brevity
PdfPCell cell204Submitted = new PdfPCell()
{
CellEvent = new DynamicCheckbox("checkbox204Submitted", "204 Submitted or on file")
};
tblFirstRow.AddCell(cell204Submitted);
doc.Add(tblFirstRow);
The DynamicCheckbox class, based on Jeff S's CustomCellLayout class, is:
public class DynamicCheckbox : IPdfPCellEvent
{
private string fieldname;
private string cap;
public DynamicCheckbox(string name, String caption)
{
fieldname = name;
cap = caption;
}
public void CellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases)
{
PdfWriter writer = canvases[0].PdfWriter;
RadioCheckField ckbx = new RadioCheckField(writer, rectangle, fieldname, "Yes");
ckbx.CheckType = RadioCheckField.TYPE_CHECK;
ckbx.Text = cap;
PdfFormField field = ckbx.CheckField;
writer.AddAnnotation(field);
}
}
My problem is that the checkbox's text (the string assigned to ckbx.Text) is not displaying. The checkbox (outsized) occupies the last cell in the table row, but there is no (visible) accompanying text.
What's missing from my code?
Note: I tried to reduce the size of the checkbox by doing this:
Rectangle tangle = new Rectangle(20, 20);
//RadioCheckField ckbx = new RadioCheckField(writer, rectangle, fieldname, "Yes");
RadioCheckField ckbx = new RadioCheckField(writer, tangle, fieldname, "Yes");
...but that attempt failed - with that code, I can't even "find" the checkbox in the generated PDF file - clicking willy-nilly in column 5 conjures up no checkbox...

Others have answered the label part. The Rectangle that you have called "tangle" needs to be calculated off of the rectangle that comes into the event handler, similar to
Rectangle tangle = new Rectangle(
rectangle.Left,
rectangle.Top - PDFStyle.boxsize - 4.5f,
rectangle.Left + PDFStyle.boxsize,
rectangle.Top - 4.5f
);
Where PDFStyle.boxsize is the width/height of the checkbox and 4.5f is the padding the edge of the cell. Basically the rectangle isn't relative to the cell, but absolute to the page.

As described in ISO-32000-1, a check box is a field of type Button. If you define text for a button, you want to define the text that is displayed on the button. However: in the case of a check box, there is no such text! Instead, you have two appearances, one for the Off value and one for the Yes value.
An educated guess made by an attentive reader would be that you don't want to add text (to the button), but that you want to add a label (for a checkbox). Again you should consult ISO-32000-1 and you'll discover that the spec doesn't say anything about labels for check boxes. The concept just doesn't exist at the level of an AcroForm.
This doesn't mean the concept doesn't exist in general. Many PDF tools allow you to define check boxes that are preceded by a label. When you look inside the PDF, you'll discover that this label is just part of the content, whereas the check box is represented by a widget orientation.
Let's take a look at the official documentation instead of frustrating ourselves searching on every place of the web except on the official web site. More specifically: let's take a look at the Buttons example from Chapter 7 of my book. You'll see that one can set text for a real button:
PushbuttonField button = new PushbuttonField(writer, rect, "Buttons");
button.setText("Push me");
This isn't possible with check boxes (for the obvious reason that the appearance of a check box is completely different). If we want to add a label, we can add it for instance like this:
checkbox = new RadioCheckField(writer, rect, LANGUAGES[i], "Yes");
field = checkbox.getCheckField();
field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", onOff[0]);
field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Yes", onOff[1]);
writer.addAnnotation(field);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
new Phrase(LANGUAGES[i], font), 210, 790 - i * 40, 0);
You can find the C# version of these examples here: http://tinyurl.com/itextsharpIIA2C07

Creating a checkbox, and then accompanying text to its right, can be done like this:
PdfPCell cell204Submitted = new PdfPCell()
{
CellEvent = new DynamicCheckbox("checkbox204Submitted")
};
tblFirstRow.AddCell(cell204Submitted);
// . . . Chunks and an anchor created; that code has been elided for brevity
Paragraph parCkbxText = new Paragraph();
parCkbxText.Add(Chunk204SubmittedPreamble);
parCkbxText.Add(ChunkBoldNote);
parCkbxText.Add(Chunk204Midsection);
parCkbxText.Add(anchorPayeeSetup204);
PdfPCell cellCkbxText = new PdfPCell(parCkbxText);
cellCkbxText.BorderWidth = PdfPCell.NO_BORDER;
tblFirstRow.AddCell(cellCkbxText);
public class DynamicCheckbox : IPdfPCellEvent
{
private string fieldname;
public DynamicCheckbox(string name)
{
fieldname = name;
}
public void CellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases)
{
PdfWriter writer = canvases[0].PdfWriter;
RadioCheckField ckbx = new RadioCheckField(writer, rectangle, fieldname, "Yes");
ckbx.CheckType = RadioCheckField.TYPE_CHECK;
ckbx.BackgroundColor = BaseColor.ORANGE;
ckbx.FontSize = 6;
ckbx.TextColor = BaseColor.WHITE;
PdfFormField field = ckbx.CheckField;
writer.AddAnnotation(field);
}
}

Related

Using a variable to name an Event Handler

Updated 10 Nov 2022
I have the following code in a Winforms program:
void CreateCheckBoxes(Control parentControl, int left, int top, int lineSpace)
{
List<string> listVariables = new List<string>() { "AllowColumnReorder", "CaptureFocusClick", "ColScaleMode", "ColumnTracking", "RowTracking", "EnsureVisible", "FullRowSelect", "GridLines", "HideSelection", "HoverSelection", "IsFocused", "LabelEdit", "MultiSelect", "Scrollable", "VisualStyles" };
foreach (string varName in listVariables)
{
CheckBox ctlTemp = new CheckBox { Name = "chk" + varName, Text = varName, Top = top, Left = left };
parentControl.Controls.Add(ctlTemp);
top += lineSpace;
}
chkAllowColumnReorder.CheckedChanged += new EventHandler(chkAllowColumnReorder_CheckedChanged);
// The name 'chkAllowColumnReorder' does not exist in the current context
}
It works to the extent that I can create as many CheckBoxes as I like based on the length of listVariables. However, I want the name of the CheckedChanged event handler to be based on the name of the control.
As well as my original question I now find I cannot refer to the CheckBox by the name provided in { Name = "chk" + varName, in the debugger a watch on "Name" returns the name of the form. I have not used this form of constructor before and am struggling to find any documentation on it. Can anybody help on this before I try to move on again please?
Is there a way to do this?
The code itself is produced by a small program where I just past in the names of variables from the main program and it produces the above, and all the vent handlers, which is an enormous time saver.
jimi - I've posted this as an answer as it's too long for a comment.
I ended up with:
Dictionary<string, Action<CheckBox>> m_Actions = new Dictionary<string, Action<CheckBox>>();
then loop through:
m_Actions.Add("chkAllowColumnReorder", (c) => containerListView1.AllowColumnReorder = c.Checked); etc.
and then:
void chkTemp_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkTemp = ((CheckBox)sender);
m_Actions[chkTemp.Name](chkTemp);
}
This is completely new to me and I'm still not sure how (or why) it works but thank you very much for telling me about it - I can now paste variables in to my app's form and produce all the code to add controls to the app I need to test.
I did it because my heart sank at the thought of adding heaps of CheckBoxes to an app to test an ExtendeListView, in the end writing this to produce the code was much more interesting than the testing!

Assigning values to array of 'Combo Boxes' in a 'Group Box' using for each loop in c#

I have 10 comboBox in a groupBox
for I just want to display a calculated value in respective comboBox like this say if I set a varible double i=08.00; then on button click cmboBox should display values like this
CB1-08.00
CB2-09.50
CB3-10.00
CB4-10.50
CB5-11.00
CB6-11.50
.... and so on upto CB10 But I am getting output like this
And Code
private void button1_Click(object sender, EventArgs e)
{
double i=08.00;
foreach (var comboBox in groupBox1.Controls.OfType<ComboBox>())
{
comboBox.Text = i.ToString("00.00");
i = i + 0.5;
}
}
Your combobox order is different in the collection so it inserts the numbers randomly. May be you can name your combobox for instance like cmb1,cmb2,cmb3 etc. and if you update your code it will run.
Your controls in the Controls collection are not sorted by their appearance on the form. You will need to find a way to sort them if you need different values in each based on their position.
Foreach loop doesn't give the collection in the order you wanted. The way to go forward is to give a tag id to each combo box, then you can use that to assign a value to them them.
So your first combo box will start with tag id 0, and the last one will have 8,
double val = 08.00;
for (int i = 0; i < groupBox1.Controls.Count; ++i)
{
var combobox = groupBox1.Controls[i] as ComboBox;
int tag = int.Parse(combobox.Tag.ToString());
double value = val + (0.5 * tag);
combobox.Text = value.ToString("00.00");
}
Make sure you tag the cobbo box in the order you wanted them.

WinForms ComboBox: text vs. selectedtext

In my WinForms / C# application, I can choose either Combobox.Text or Combobox.SelectedText to return the string value of what's been selected. What's the difference, and when would I choose one over the other?
SelectedText is what's highlighted. Depending on the DropDownStyle property, users can select a part of the visible text.
For example, if the options are:
Democrat
Republican
Independent
Other
A user can select the letters "Dem" in Democrat - this would be the SelectedText. This works with the ComboBoxStyle.Simple or ComboBoxStyle.DropDown, but NOT with ComboBoxStyle.DropDownList, since the third style does not allow selecting a portion of the visible item (or adding new items).
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedtext.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx
However, using the Text property, you can pre-select an option (by setting the Text to "Other", for example, you could select the last item.)
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.text.aspx
I find it easier to see the difference using a text box:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "Text in combo box 1";
textBox2.Text = "Text in combo box 2";
button1.Focus();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox2.SelectedText);
}
In textbox2, select part of the text and click the button.
I've used this before for primitive spell checkers, when you only want to highlight part of the textbox (not the whole value)
Try this one. It helps when the DropDownStyle property is set to DropDownList.
public string GetProdName(int prodID)
{
string s = "";
try
{
ds = new DataSet();
ds = cmng.GetDataSet("Select ProductName From Product where ProductID=" + prodID + "");
if (cmng.DSNullCheck(ds) && cmng.DSRowCheck(ds))
{
s = ds.Tables[0].Rows[0][0].ToString();
}
}
catch {
}
return s;
}
In the click event:
lblProduct.Text = GetProdName((int)ddlProduct.SelectedValue);
If you want to read an item text which is in a combobox, you can use [comboboxname].SelectedItem.ToString().
If you want to read an item value, use [comboboxname].SelectedValue.

How to format specific text in WPF?

I have this code that adds dotted lines under text in text box:
// Create an underline text decoration. Default is underline.
TextDecoration myUnderline = new TextDecoration();
// Create a linear gradient pen for the text decoration.
Pen myPen = new Pen();
myPen.Brush = new LinearGradientBrush(Colors.White, Colors.White, new Point(0, 0.5), new Point(1, 0.5));
myPen.Brush.Opacity = 0.5;
myPen.Thickness = 1.0;
myPen.DashStyle = DashStyles.Dash;
myUnderline.Pen = myPen;
myUnderline.PenThicknessUnit = TextDecorationUnit.FontRecommended;
// Set the underline decoration to a TextDecorationCollection and add it to the text block.
TextDecorationCollection myCollection = new TextDecorationCollection();
myCollection.Add(myUnderline);
PasswordSendMessage.TextDecorations = myCollection;
My problem is I need only the last 6 characters in the text to be formatted!
Any idea how can I achieve that?
Instead of setting the property on the entire TextBlock, create a TextRange for the last six characters and apply the formatting to that:
var end = PasswordSendMessage.ContentEnd;
var start = end.GetPositionAtOffset(-6) ?? PasswordSendMessage.ContentStart;
var range = new TextRange(start, end);
range.ApplyPropertyValue(Inline.TextDecorationsProperty, myCollection);
If PasswordSendMessage is a TextBox rather than a TextBlock, then you cannot use rich text like this. You can use a RichTextBox, in which case this technique will work but you will need to use PasswordSendMessage.Document.ContentEnd and PasswordSendMessage.Document.ContentStart instead of PasswordSendMessage.ContentEnd and PasswordSendMessage.ContentStart.
You could databind your text to the Inlines property of TextBox and make a converter to build the run collection with a seperate Run for the last 6 characters applying your decorations

Silverlight specific Image shifting to the right

I am generating a set images to form a human body so that I can use for a physics engine.
The images generated are in a specific user control in where I set the dimentions and co-ordinates of each image. That usercontrol is then loaded in another user control but for some reason when the images are loaded, one specific image which I named (rightBicep) is shifting to the right. Here is a screenshot :
alt text http://img193.imageshack.us/img193/592/imageshift.jpg
I illustrated the positions of the images with dotted lines, the green dotted line is refering to where the image should be located, and the red dotted line is where the image is being shown.
The weird thing is the image beneath it (called rightForearm) take's it's LeftPosition from it, and when during debugging they have the exact same leftProperty value. Here's the syntax :
public void generateRightBicep(string imageUrl)
{
rightBicep = new Image();
rightBicep.Name = CharacterName + "rightbicep";
Uri imageUri = new Uri(imageUrl, UriKind.Relative);
LayoutRoot.Children.Add(rightBicep);
rightBicep.Source = new BitmapImage(imageUri);
rightBicep.ImageOpened += new EventHandler<RoutedEventArgs>(bodyPart_ImageOpened);
}
public void rightBicepLoaded()
{
var bi = waitTillImageLoad(rightBicep.Name);
rightBicep.Height = elbowToArmpit + (2 * palm);
rightBicep.Width = ratio(bi.PixelHeight, bi.PixelHeight, rightBicep.Height); // to be determined
Vector2 topVector;
topVector.X = (float)(Convert.ToDouble(torso.GetValue(Canvas.LeftProperty)) - palm);
topVector.Y = (float)(Convert.ToDouble(neck.GetValue(Canvas.TopProperty)) + neck.Height);
if (!faceRight)
{
perspectiveVectorHeight(ref topVector, ref rightBicep, torso.Width);
rightBicep.Width = ratio(bi.PixelHeight, bi.PixelHeight, rightBicep.Height);
}
rightBicep.SetValue(Canvas.LeftProperty, Convert.ToDouble(topVector.X));
rightBicep.SetValue(Canvas.TopProperty, Convert.ToDouble(topVector.Y));
rightBicep.SetValue(Canvas.ZIndexProperty, rightBicepZindex);
generateRightShoulder();
}
public void generateRightForearm(string imageUrl)
{
rightForearm = new Image();
rightForearm.Name = CharacterName + "rightforearm";
Uri imageUri = new Uri(imageUrl, UriKind.Relative);
LayoutRoot.Children.Add(rightForearm);
rightForearm.Source = new BitmapImage(imageUri);
rightForearm.ImageOpened += new EventHandler<RoutedEventArgs>(bodyPart_ImageOpened);
}
public void rightForearmLoaded()
{
var bi = waitTillImageLoad(rightForearm.Name);
rightForearm.Height = (elbowToHandTip - handLength) + palm;
rightForearm.Width = ratio(bi.PixelHeight, bi.PixelWidth, rightForearm.Height);
Vector2 topVector;
if (faceRight)
{
topVector.X = (float)(Convert.ToDouble(rightBicep.GetValue(Canvas.LeftProperty)));
topVector.Y = (float)(Convert.ToDouble(rightBicep.GetValue(Canvas.TopProperty)) + rightBicep.Height - palm);
}
else
{
topVector.X = (float)(Convert.ToDouble(leftBicep.GetValue(Canvas.LeftProperty)));
topVector.Y = (float)(Convert.ToDouble(leftBicep.GetValue(Canvas.TopProperty)) + leftBicep.Height - palm);
perspectiveVectorHeight(ref topVector, ref rightForearm, torso.Width);
rightForearm.Width = ratio(bi.PixelHeight, bi.PixelWidth, rightForearm.Height);
}
rightForearm.SetValue(Canvas.LeftProperty, Convert.ToDouble(topVector.X));
rightForearm.SetValue(Canvas.TopProperty, Convert.ToDouble(topVector.Y));
rightForearm.SetValue(Canvas.ZIndexProperty, rightForearmZIndex);
generateRightElbow();
}
Now all the values I am adding together are a group of doubles I preset, and the property faceRight is to dertmine if the human body is facing right or left to determine where the positions of the body parts (since if the right hand looks on the left hand side when the human body turns the other way).
If you notice the rightforearm is taking the leftproperty of the rightbicep, so technically it should display direcrly underneath which it isn't. I also debugged the user control and both have the left property of -3.
PS. I call the methods rightbicepLoaded and rightforearmLoaded when an event is called when all the imageOpened events all have been triggered.
Any ideas on why this is happening?
Found out why , in my method ratio it should take hieght and width, and I put and i put 2 hieghts instead

Resources