So, I've seen an example for a newly created doc
Rectangle r = new Rectangle(400, 300);
Document doc = new Document(r);
try
{
PdfWriter.GetInstance(doc, new FileStream("C:/Blocks2.pdf", FileMode.Create));
doc.Open();
string text = #"The result can be seen below, which shows the text
having been written to the document but it looks a
mess. ";
text = text.Replace(Environment.NewLine, String.Empty).Replace(" ", String.Empty);
Font brown = new Font(Font.FontFamily.COURIER, 9f, Font.NORMAL, new BaseColor(163, 21, 21));
Font lightblue = new Font(Font.FontFamily.COURIER, 9f, Font.NORMAL, new BaseColor(43, 145, 175));
Font courier = new Font(Font.FontFamily.COURIER, 9f);
Font georgia = FontFactory.GetFont("georgia", 10f);
georgia.Color = BaseColor.GRAY;
Chunk beginning = new Chunk(text, georgia);
Phrase p1 = new Phrase(beginning);
Chunk c1 = new Chunk("You can of course force a newline using \"", georgia);
Chunk c2 = new Chunk(#"\n", brown);
Chunk c3 = new Chunk("\" or ", georgia);
Chunk c4 = new Chunk("Environment", lightblue);
Chunk c5 = new Chunk(".NewLine", courier);
Chunk c6 = new Chunk(", or even ", georgia);
Chunk c7 = new Chunk("Chunk", lightblue);
Chunk c8 = new Chunk(".NEWLINE", courier);
Chunk c9 = new Chunk(" as part of the string you give a chunk.", georgia);
Phrase p2 = new Phrase();
p2.Add(c1);
p2.Add(c2);
p2.Add(c3);
p2.Add(c4);
p2.Add(c5);
p2.Add(c6);
p2.Add(c7);
p2.Add(c8);
p2.Add(c9);
Paragraph p = new Paragraph();
p.Add(p1);
p.Add(p2);
p.Alignment = Element.ALIGN_JUSTIFIED;
doc.Add(p);
}
As you can see, the document is initiated with a rectangle Document doc = new Document(r);
So, the result of this code is gonna be like this
My question is: how do I append text, which will consider page size in an existing document?
Is it possible to add a rectangle with a text in a doc? Or maybe append a newly created document to an existing one?
I realise, that I should probably read iText books, but I'm kind of running out of time and this is the last thing I have to figure out. Is there a clean easy solution, to my question? Thank you
UPDATE:
Sadly, for some reason the solution by Alexis Pigeon doesn't work for me.
I've written
Document doc = new Document();
var writer = PdfWriter.GetInstance(doc, new FileStream("C:/Blocks2.pdf", FileMode.Open));
doc.Open();
and at the end
doc.Add(p); doc.Close()
And no changes are applied to the file, although code runs smoothly.
Something tells me, that this approach is wrong, since I haven't met any code examples, where people would have used Document with and existing pdf file, only creating a new one. Usually it's PDFStamper or PDFWriter.
So, let me rephrase my question: How do I append text to an existing document so that it will fill certain rectangle?
So, after looking around I figured out, that what Im looking for is called "hyphenation". Didnt know this word.
To fit the text in a rectangle area you need to create a table with one cell and invisible borders. I've also encoutered issues with encoding. Here is the code.:
PdfReader pdf = new PdfReader("Test1.pdf");
File.Delete("C:/Blocks.pdf");
PdfStamper stp = new PdfStamper(pdf, new FileStream("C:/Blocks.pdf", FileMode.OpenOrCreate));
var canvas = stp.GetOverContent(1);
PdfPTable table = new PdfPTable(1);
table.SetTotalWidth(new float[] { 100 });
Phrase phrase = new Phrase();
phrase.Hyphenation = new HyphenationAuto("ru", "RU", 2, 2);
var bf = BaseFont.CreateFont("c:/windows/fonts/arialbd.ttf", "Cp1251", BaseFont.EMBEDDED);
phrase.Add(new Chunk("О БОЖЕ ТЫ МОЙ НЕУЖЕЛИ РАБОТАЕТ ЕСЛИ РАБОТАЕТ Я БЫЛ БЫ ТАК СЧАСТЛИВ", new Font(bf, 12)));
PdfPCell cell = new PdfPCell(phrase);
cell.Border = Rectangle.NO_BORDER;
table.AddCell(cell);
table.WriteSelectedRows(0, 1, 200, 200, canvas);
stp.Close();
Related
So I am trying to convert a standard A4 PDF file into a .txt file using Spire.Pdf NuGet Package, and whenever I do it there is a lot of whitespace at the start of each line where the margins of the document go I presume. I managed to solve the issue using the TrimStart() method but I want to be able to do remove the margins using Spire.Pdf itself.
I have played around with setting a PdfTextExtractOptions ExtractArea RectangleF but for some reason it cuts the bottom of the text and I lose rows.
My code is:
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(#"path");
var content = new List<string>();
RectangleF rectangle = new RectangleF(45, 0, 0, 0);
PdfTextExtractOptions options = new() { IsExtractAllText = true, IsShowHiddenText = true, ExtractArea = rectangle };
foreach (PdfPageBase page in doc.Pages)
{
PdfTextExtractor textExtractor = new(page);
//extract text from a specific rectangular area here - defualt A4 margin sizes?
string extractedText = textExtractor.ExtractText(options);
content.Add(extractedText);
}
FileStream fs = new FileStream(#"outputFile.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
string txtBefore = (string.Join("\n", content));
sw.Write(txtBefore);
Thanks in advance
You can try the code below to extract text from PDF, it will not generate extra white spaces at the start of each line in the result .txt file. I already tested it.
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(#"test.pdf");
PdfTextExtractOptions options = new PdfTextExtractOptions();
options.IsSimpleExtraction = true;
StringBuilder sb = new StringBuilder();
foreach (PdfPageBase page in doc.Pages)
{
PdfTextExtractor extractor = new PdfTextExtractor(page);
sb.AppendLine(extractor.ExtractText(options));
}
File.WriteAllText("Extract.txt", sb.ToString());
I'm working on making a little program that just takes a .txt file and converts it into a PDF, and I want the PDF to look similar to how the text file would look if I used Microsoft's Print to PDF. I have it pretty close, but when a line of text exceeds the width of the page it wraps to a new line and the wrapped text overlaps the text above it. How do I get the wrapped text to behave as if I'm adding a new paragraph to the document without splitting the wrapped text into a new paragraph?
Here's my old code:
string dest = #"..\TXT2PDF\Test.pdf";
string source = #"..\TXT2PDF\test2.txt";
string fpath = #"..\TXT2PDF\consola.ttf";
string line;
FileInfo destFile = new FileInfo(dest);
destFile.Directory.Create();
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
PageSize ps = new PageSize(612, 792);
pdf.SetDefaultPageSize(ps);
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.CreateFont(fpath);
StreamReader file = new StreamReader(source);
Console.WriteLine("Beginning Conversion");
document.SetLeftMargin(54);
document.SetRightMargin(54);
document.SetTopMargin(72);
document.SetBottomMargin(72);
while ((line = file.ReadLine()) != null)
{
Paragraph p = new Paragraph();
p.SetFixedLeading(4.8f);
p.SetFont(font).SetFontSize(10.8f);
p.SetPaddingTop(4.8f);
p.Add("\u00A0");
p.Add(line);
document.Add(p);
}
document.Close();
file.Close();
Console.WriteLine("Conversion Finished");
Console.ReadLine();
Here's my new code:
string dest = #"..\TXT2PDF\Test.pdf";
string source = #"..\TXT2PDF\test2.txt";
string fpath = #"..\TXT2PDF\consola.ttf";
string line;
FileInfo destFile = new FileInfo(dest);
destFile.Directory.Create();
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
PageSize ps = new PageSize(612, 792);
pdf.SetDefaultPageSize(ps);
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.CreateFont(fpath, "cp1250", true);
StreamReader file = new StreamReader(source);
Console.WriteLine("Beginning Conversion");
document.SetLeftMargin(54);
document.SetRightMargin(54);
document.SetTopMargin(68);
document.SetBottomMargin(72);
document.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 1.018f));
Paragraph p = new Paragraph();
p.SetFont(font).SetFontSize(10.8f);
p.SetCharacterSpacing(0.065f);
string nl = "";
while ((line = file.ReadLine()) != null)
{
Text t = new Text(nl + "\u0000" + line);
p.Add(t);
nl = "\n";
}
document.Add(p);
document.Close();
file.Close();
Console.WriteLine("Conversion Finished");
Console.ReadLine();
Here's an example of what the output looks like:
Edit
With mkl's recommendation I replaced p.SetFixedLeading(4.8f) with document.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 1.018f)). That fixed the spacing issue for the wrapped text, but it caused the space between the paragraphs to increase more than I wanted. In order to get around that, I decided to only use one paragraph object and add each line as a new text object to the paragraph. I had tried that once before, but the text objects weren't going on new lines. I had to add the new line character to the beginning of each text object in order for them to be on their own line.
This is how the output looks now:
Rather than making each line from the txt file be a new paragraph, I changed each line to be a new text object, then I added each text object to a single paragraph. I then stopped using fixed leading on the paragraph and started using multiplied leading on the document itself using document.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 1.018f)). I could've also used p.SetMultipliedLeading(1.018f) though. This achieved my desired spacing in the document.
I want to create a PDF file with Arabic text content in C#. I'm using iTextSharp to create this. I followed the instruction in http://geekswithblogs.net/JaydPage/archive/2011/11/02/using-itextsharp-to-correctly-display-hebrew--arabic-text-right.aspx. I want to insert the following Arabic sentence in pdf.
تم إبرام هذا العقد في هذا اليوم [●] م الموافق [●] من قبل وبين .
The [●] need to be replaced by dynamic English words. I tried to implement this by using ARIALUNI.TTF [This tutorial link suggested it]. The code is given below.
public void WriteDocument()
{
//Declare a itextSharp document
Document document = new Document(PageSize.A4);
//Create our file stream and bind the writer to the document and the stream
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(#"D:\Test.Pdf", FileMode.Create));
//Open the document for writing
document.Open();
//Add a new page
document.NewPage();
//Reference a Unicode font to be sure that the symbols are present.
BaseFont bfArialUniCode = BaseFont.CreateFont(#"D:\ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//Create a font from the base font
Font font = new Font(bfArialUniCode, 12);
//Use a table so that we can set the text direction
PdfPTable table = new PdfPTable(1);
//Ensure that wrapping is on, otherwise Right to Left text will not display
table.DefaultCell.NoWrap = false;
//Create a regex expression to detect hebrew or arabic code points
const string regex_match_arabic_hebrew = #"[\u0600-\u06FF,\u0590-\u05FF]+";
if (Regex.IsMatch("م الموافق", regex_match_arabic_hebrew, RegexOptions.IgnoreCase))
{
table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
}
//Create a cell and add text to it
PdfPCell text = new PdfPCell(new Phrase(" : "+"من قبل وبين" + " 2007 " + "م الموافق" + " dsdsdsdsds " + "تم إبرام هذا العقد في هذا اليوم ", font));
//Ensure that wrapping is on, otherwise Right to Left text will not display
text.NoWrap = false;
//Add the cell to the table
table.AddCell(text);
//Add the table to the document
document.Add(table);
//Close the document
document.Close();
//Launch the document if you have a file association set for PDF's
Process AcrobatReader = new Process();
AcrobatReader.StartInfo.FileName = #"D:\Test.Pdf";
AcrobatReader.Start();
}
While calling this function, I got a PDF with some Unicode as given below.
اذه يف دقعلا اذه ماربإ مت dsdsdsdsds قفاوملا م 2007 نيبو لبق نم
مويلا
It is not matching with our hard coded Arabic sentence. Is this a issue of font? Please help me or suggest me any other method to implement the same.
#csharpcoder has the right idea, but his execution is off. He doesn't add the cell to a table, and the table doesn't end up in the document.
void Go()
{
Document doc = new Document(PageSize.LETTER);
string yourPath = "foo/bar/baz.pdf";
using (FileStream os = new FileStream(yourPath, FileMode.Create))
{
PdfWriter.GetInstance(doc, os); // you don't need the return value
doc.Open();
string fontLoc = #"c:\windows\fonts\arialuni.ttf"; // make sure to have the correct path to the font file
BaseFont bf = BaseFont.CreateFont(fontLoc, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);
PdfPTable table = new PdfPTable(1); // a table with 1 cell
Phrase text = new Phrase("العقد", f);
PdfPCell cell = new PdfPCell(text);
table.RunDirection = PdfWriter.RUN_DIRECTION_RTL; // can also be set on the cell
table.AddCell(cell);
doc.Add(table);
doc.Close();
}
}
You will probably want to get rid of the cell borders etc, but that information can be found elsewhere on SO or the iText website. iText should be able to handle text that contains both RTL and LTR characters.
EDIT
I think the source problem is actually with how the Arabic text is rendered in Visual Studio and in Firefox (my browser), or alternatively with how the Strings are concatenated. I'm not very familiar with Arabic text editors, but the text seems to come out correctly if we do this:
FYI I had to take a screenshot, because copy-pasting into the browser from VS (and vice versa) messes up the order of the parts of the text.
Right-to-left writing and Arabic ligatures are only supported in ColumnText and PdfPTable!
Try out the below code :
Document Doc = new Document(PageSize.LETTER);
//Create our file stream
using (FileStream fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read))
{
//Bind PDF writer to document and stream
PdfWriter writer = PdfWriter.GetInstance(Doc, fs);
//Open document for writing
Doc.Open();
//Add a page
Doc.NewPage();
//Full path to the Unicode Arial file
string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arabtype.TTF");
//Create a base font object making sure to specify IDENTITY-H
BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);
//Write some text, the last character is 0x0278 - LATIN SMALL LETTER PHI
Doc.Add(new Phrase("This is a ميسو ɸ", f));
//add Arabic text, for instance in a table
PdfPCell cell = new PdfPCell();
cell.AddElement(new Phrase("Hello\u0682", f));
cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
//Close the PDF
Doc.Close();
}
I hope these notes can help you from other answers:
Use a safe code to achieve your font:
var tahomaFontFile = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"Tahoma.ttf");
Use BaseFont.IDENTITY_H and BaseFont.EMBEDDED properties.
var tahomaBaseFont = BaseFont.CreateFont(tahomaFontFile,
BaseFont.IDENTITY_H,
BaseFont.EMBEDDED);
var tahomaFont = new Font(tahomaBaseFont, 8, Font.NORMAL);
Use PdfWriter.RUN_DIRECTION_RTL, for both your cell and your table:
var table = new PdfPTable(1)
{
RunDirection = PdfWriter.RUN_DIRECTION_RTL
};
var phrase = new Phrase("تم إبرام هذا العقد في هذا اليوم [●] م الموافق [●] من قبل وبين .",
tahomaFont);
var cell = new PdfPCell(phrase)
{
RunDirection = PdfWriter.RUN_DIRECTION_RTL,
Border = 0,
};
i believe your problem in string structure part, try to use the below code it works fine with me, Good Luck.`
public static void GeneratePDF()
{
//Declare a itextSharp document
Document document = new Document(PageSize.A4);
Random ran = new Random();
string PDFFileName = string.Format(#"C:\Test{0}.Pdf", ran);
//Create our file stream and bind the writer to the document and the stream
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(PDFFileName, FileMode.Create));
//Open the document for writing
document.Open();
//Add a new page
document.NewPage();
var ArialFontFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.ttf");
//Reference a Unicode font to be sure that the symbols are present.
BaseFont bfArialUniCode = BaseFont.CreateFont(ArialFontFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//Create a font from the base font
Font font = new Font(bfArialUniCode, 12);
//Use a table so that we can set the text direction
var table = new PdfPTable(1)
{
RunDirection = PdfWriter.RUN_DIRECTION_RTL,
};
//Ensure that wrapping is on, otherwise Right to Left text will not display
table.DefaultCell.NoWrap = false;
ContentObject CO = new ContentObject();
CO.Name = "Ahmed Gomaa";
CO.StartDate = DateTime.Now.AddMonths(-5);
CO.EndDate = DateTime.Now.AddMonths(43);
string content = string.Format(" تم إبرام هذا العقد في هذا اليوم من قبل {0} في تاريخ بين {1} و {2}", CO.Name, CO.StartDate, CO.EndDate);
var phrase = new Phrase(content, font);
//var phrase = new Phrase("الحمد لله رب العالمين", font);
//Create a cell and add text to it
PdfPCell text = new PdfPCell(phrase)
{
RunDirection = PdfWriter.RUN_DIRECTION_RTL,
Border = 0
};
//Ensure that wrapping is on, otherwise Right to Left text will not display
text.NoWrap = false;
//Add the cell to the table
table.AddCell(text);
//Add the table to the document
document.Add(table);
//Close the document
document.Close();
//Launch the document if you have a file association set for PDF's
Process AcrobatReader = new Process();
AcrobatReader.StartInfo.FileName = PDFFileName;
AcrobatReader.Start();
}
}
public class ContentObject
{
public string Name { set; get; }
public DateTime StartDate { set; get; }
public DateTime EndDate { set; get; }
}
`
I want to decorate various paragraphs in a PDF file by bolding some text, using different fonts, and colors. I thought I found the code for how to do that (below), but it's not working - all the text is the same font, color (black), and size. Why are my virtual sweat-inducing efforts to prettyify the PDF file so far in vain? Here is my code:
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 50, 50, 25, 25))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
// Mimic the appearance of Duckbill_Platypus.pdf
var docTitle = new Paragraph("Duckbilled Platypi - they're not what's for dinner");
var titleFont = FontFactory.GetFont("Courier", 18, BaseColor.BLACK);
docTitle.Font = titleFont;
doc.Add(docTitle);
var subTitle = new Paragraph("Baby, infant, toddler, and perhaps 'Terrible 2s' Platypi are called Platypups");
var subtitleFont = FontFactory.GetFont("Times Roman", 13, BaseColor.BLACK);
subTitle.Font = subtitleFont;
doc.Add(subTitle);
var importantNotice = new Paragraph("Teenage platypi are sometimes called Platydude[tte]s");
var importantNoticeFont = FontFactory.GetFont("Courier", 13, BaseColor.RED);
importantNotice.Font = importantNoticeFont;
doc.Add(importantNotice);
ListColumns lc;
for (int i = 0; i < listOfListItems.Count; i++)
{
lc = listOfListItems[i];
sb.AppendLine(String.Format(#"<p>Request date is {0}; Payee Name is {1}; Remit Address or Mail Stop is {2}; Last 4 of SSN or ITIN is {3}; 204 Submitted or on file is {4}; Requester Name is {5}; Dept or Div Name is {6}; Phone is {7}; Email is {8}</p>",
lc.li_requestDate, lc.li_payeeName, lc.li_remitAddressOrMailStop, lc.li_last4SSNDigitsOrITIN, lc.li_204SubmittedOrOnFile, lc.li_requesterName, lc.li_deptDivName, lc.li_phone, lc.li_email));
}
String htmlToRenderAsPDF = sb.ToString();
//XMLWorker also reads from a TextReader and not directly from a string
using (var srHtml = new StringReader(htmlToRenderAsPDF))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
}
doc.Close();
}
}
try
{
var bytes = ms.ToArray();
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "iTextSharpTest.pdf");
File.WriteAllBytes(testFile, bytes);
}
catch (Exception ex)
{
String exMsg = ex.Message;
; // what is "ex" here?
}
I'm setting two sizes of font (18 and 13), two colors (black and red), two fonts ("Courier" and "Times Roman") yet all my hours of travail here for PDF fancification seem yet in vain (apologies to Vachel Lindsay and Abraham Lincoln).
You should use the font when creating the Paragraph:
Font f = new Font(FontFamily.COURIER);
Paragraph p = new Paragraph("text", f);
document.add(p);
Or you should wait to add content until you've set the font:
Paragraph p = new Paragraph();
Font f = new Font(FontFamily.COURIER);
p.setFont(f);
p.addText("text");
document.add(p);
In your code, you have something like this:
Paragraph p = new Paragraph("text");
Font f = new Font(FontFamily.COURIER);
p.setFont(f);
document.add(p);
When setting the font using setFont(), you set the font for the text that will be added to the paragraph, not to the text that is already stored in the paragraph.
For instance:
Paragraph p = new Paragraph("font 1 ");
p.setFont(new Font(FontFamily.COURIER);
p.add("font 2");
document.add(p);
This will add the text font 1 in the default font and font 2 in Courier.
I am using iTextSharp and CSharp for creating the pdf. I need to add formfields like checkbox, radiobutton and dropdown which can not be edited.
I used this..
FileStream pdffile = new FileStream(path + "/Pdf/tes.pdf",FileMode.Create);
PdfWriter writer = PdfWriter.GetInstance(doc, pdffile);
doc.Open();
Rectangle rect = new Rectangle(100, 100, 100, 100);
RadioCheckField checkbox = new RadioCheckField(writer, rect, "bhjabsdf", "on");
checkbox.CheckType = RadioCheckField.TYPE_CHECK;
PdfFormField field = checkbox.CheckField;
writer.AddAnnotation(field);
doc.Close();
But it's not working. I also read about PdfStamper. But I am creating a new pdf, not changing the existing one.So I don't know whether I can use PdfStamper?
Thanks..
Edit:
private void CreateRadioButton(PdfWriter writer, PdfContentByte cb,Font font)
{
Rectangle rect;
PdfFormField field;
PdfFormField radiogroup = PdfFormField.CreateRadioButton(writer, true);
radiogroup.FieldName = "language";
RadioCheckField radio;
int x = 20;
for (int i = 0; i < Petrol.Length; i++)
{
rect = new Rectangle(440 + i * x, 692, 450 + i * x, 682);
radio = new RadioCheckField(writer, rect, null, LANGUAGES[i]);
radio.BorderColor = GrayColor.GRAYBLACK;
radio.BackgroundColor = BaseColor.WHITE;
radio.CheckType = RadioCheckField.TYPE_CIRCLE;
if (Petrol[i] == "F")
radio.Checked = true;
field = radio.RadioField;
//Here i am setting readonly..
field.SetFieldFlags(PdfFormField.FF_READ_ONLY);
radiogroup.AddKid(field);
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
new Phrase(Petrol[i], font), 451 + i * x, 684, 0);
if (i >= 1) x = 25;
}
writer.AddAnnotation(radiogroup);
}
You're creating a field 'the hard way'. There's a class named RadioCheckField that makes it much easier for you to create a field.
Please take a look at the book examples from Chapter 8. You can find C# versions of the examples here, for instance an example named Buttons.
checkbox = new RadioCheckField(writer, rect, LANGUAGES[i], "on");
checkbox.CheckType = RadioCheckField.TYPE_CHECK;
PdfFormField field = checkbox.CheckField;
You can create your custom form template using LiveCycle and then data bind the form fields using iTextSharp like this
string randomFileName = Helpers.GetRandomFileName();
string formTemplate = Server.MapPath("~/FormTemplate.pdf");
string formOutput = Server.MapPath(string.Format("~/downloads/Forms/Form-{0}.pdf", randomFileName));
PdfReader reader = new PdfReader(formTemplate);
PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(formOutput, System.IO.FileMode.Create));
AcroFields fields = stamper.AcroFields;
// set form fields
fields.SetField("Date", DateTime.Now.ToShortDateString());
fields.SetField("FirstName", user.FirstName);
fields.SetField("LastName", user.LastName);
fields.SetField("Address1", user.Address1);
fields.SetField("Address2", user.Address2);
fields.SetField("City", user.City);
fields.SetField("State", user.State);
fields.SetField("Zip", user.Zip);
fields.SetField("Email", user.Email);
fields.SetField("Phone", user.Phone);
// set document info
System.Collections.Hashtable info = new System.Collections.Hashtable();
info["Title"] = "User Information Form";
info["Author"] = "My Client";
info["Creator"] = "My Company";
stamper.MoreInfo = info;
// flatten form fields and close document
stamper.FormFlattening = true;
stamper.Close();
You do not need to use a PdfStamper to create AcroForm form fields in a PDF, PdfWriter also allows you to.
Unfortunately you neither said in which way your code didn't work nor what exact requirements you have; still some sample code might bring you on track:
Have a look at chapter 8 of iText in Action, 2nd edition; especially the sample Buttons will give you numerous hints on how to create radio buttons and check boxes. The sample ChoiceFields will show you how to create list and combo boxes.