This question already has an answer here:
- How to display ✔ in PDF using iTextSharp? 2 answers
I am using iTextSharp v5.5.11 and I want to amend the following code to display a checked checkbox (may not necessarily need a checkbox control; an equivalent checked checkbox icon or similar would do) in the PDF that is generated. The code I have so far produced a checkbox which is not checked on PDF generation. As hinted, there may be better way to do this. Here is the code I have so far. Please help:
using System;
using System.Collections.Generic;
using System.IO;
using Carnotaurus.UtilityPack.Extensions.PrimitiveExtensions;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace Carno.GhostPubs.WindowsFormsApp
{
public static class PdfITextSharpExtensions
{
public static void CreatePdf(this Document doc, IReadOnlyList<string> lines, int pageSize,
string outputFullFilePath)
{
try
{
var writer = PdfWriter.GetInstance(doc,
new FileStream(outputFullFilePath, FileMode.Create, FileAccess.Write, FileShare.None));
doc.Open();
for (var index = 0; index <= lines.Count - 1; index++)
{
var mod = index % pageSize;
if (mod == 0 && index > 0)
{
doc.NewPage();
}
var field = lines[index];
doc.Add(new Paragraph(field));
var cb = writer.DirectContent;
var onOff = new PdfAppearance[2];
onOff[0] = cb.CreateAppearance(20, 20);
onOff[0].Rectangle(1, 1, 18, 18);
onOff[0].Stroke();
onOff[1] = cb.CreateAppearance(20, 20);
onOff[1].SetRGBColorFill(255, 128, 128);
onOff[1].Rectangle(1, 1, 18, 18);
onOff[1].FillStroke();
onOff[1].MoveTo(1, 1);
onOff[1].LineTo(19, 19);
onOff[1].MoveTo(1, 19);
onOff[1].LineTo(19, 1);
onOff[1].Stroke();
var rect = new Rectangle(180, 806 - index * 40, 200, 788 - index * 40);
var checkFieldName = field.RemoveSpaces();
var radioCheckField = new RadioCheckField(writer, rect, checkFieldName, "On");
var checkField = radioCheckField.CheckField;
checkField.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, "On", onOff[1]);
checkField.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", onOff[0]);
// checkField.ValueAsName = "On";
writer.AddAnnotation(checkField);
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
new Phrase(field, new Font(Font.FontFamily.HELVETICA, 18)), 210, 790 - index * 40, 0);
cb = writer.DirectContent;
}
}
catch (Exception ex)
{
}
finally
{
doc.Close();
}
}
}
}