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.
Related
I am using ASP for this and I had to generate reports in PDF format and send the file back to clients so they can download it.
I made the reports using MigraDoc library and they were great but after I tried it with Arabic text I found the texts were in LTR and the characters were disjointed so I made this code to test things out
...............
MigraDoc.DocumentObjectModel.Document reportDoc = new MigraDoc.DocumentObjectModel.Document();
reportDoc.Info.Title = "test";
sec = reportDoc.AddSection();
string fileName = "test.pdf";
addformattedText(sec, "العبارة", true);
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = reportDoc;
renderer.RenderDocument();
MemoryStream pdfStream = new MemoryStream();
renderer.PdfDocument.Save(pdfStream);
byte[] bytes = pdfStream.ToArray();
...............
private void addformattedText(Section sec,string text, bool shouldBeBold = false)
{
var tf = sec.AddTextFrame();
var p = tf.AddParagraph(text);
p.Format.Font.Name = "Tahoma";
if (shouldBeBold) p.Format.Font.Bold = true;
}
I get the output like this
I have tried to encode the text and make it a unicode string using this code
private string getEscapedString(string text)
{
if (true || HasArabicCharacters(text))
{
string uString = "";
byte[] utfBytes = Encoding.Unicode.GetBytes(text);
foreach (var u in utfBytes)
{
if (u != 0)
{
uString += String.Format(#"\u{0:x4}", u);
}
}
return uString;
}
else
return text;
}
and get the returned string into a paragraph and save the PDF documents with unicode parameter set to true
But it is all the same.
I can not figure out how to get it done.
The reports were done using MigraDoc 1.50.5147 library.
The problem is Arabic language font have 4 different shap in begging,last,connected and alone, where Pdfsharp and MigraDoc can not recognize which shap to print farther more you need to reverse the character order to solve this you can use AraibcPdfUnicodeGlyphsResharper to help do such work as following:
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using AraibcPdfUnicodeGlyphsResharper;
namespace MigraDocArabic
{
internal class PrintArabicUsingPdfSharp
{
public PrintArabicUsingPdfSharp(string path)
{
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Arial", 20, XFontStyle.BoldItalic);
var xArabicString = "كتابة اللغة العربية شيئ جميل".ArabicWithFontGlyphsToPfd();
// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
gfx.DrawString(xArabicString, font, XBrushes.Black, new XRect(50, 50, page.Width, page.Height), XStringFormats.Center);
// Save the document...
document.Save(path);
}
}
}
Do not Forget the Extension method
By the way this is work with iText7 too
see the image for result
Result
PDFsharp does not support RTL languages yet:
http://www.pdfsharp.net/wiki/PDFsharpFAQ.ashx#Does_PDFsharp_support_for_Arabic_Hebrew_CJK_Chinese_Japanese_Korean_6
You can work around this limitation by reversing the string.
PDFsharp does not support font ligatures yet. You are probably able to work around this limitation by replacing letters with the correct glyph (start, middle, end) depending on the position.
For the past week or so this exception is causing me a headache, I can't for the life of me fix it. I'm using iTextSharp to merge PDF files and add a watermark on them if the user chooses to do so.
Here's the code for merging :
private void CreateMergedPdf(object sender, DoWorkEventArgs e)
{
using (FileStream stream = new FileStream(pdfname, FileMode.Create)) {
Document pdfDoc = new Document(PageSize.A4);
PdfCopy pdf = new PdfCopy(pdfDoc, stream);
pdfDoc.Open();
int i = 0;
foreach (File_class newpdf in AddedPDFs)
{
(sender as BackgroundWorker).ReportProgress(i++);
if (newpdf.toMerge)
{
PdfReader reader = new PdfReader(newpdf.file_path);
pdf.AddDocument(reader); //<!> Exception here
this.Dispatcher.Invoke(() => progBtxt.Text = "Merging file #" + newpdf.file_id + "..."); //Dispatcher.Invoke since UI is on seperate thread
if (add_wtrmk)//This is called for every FILE
{
AddWatermark(reader, stream);
}
}
}
}
}
And here's the code for the watermark:
private void AddWatermark(PdfReader reader, FileStream stream)
{
using (PdfStamper pdfStamper = new PdfStamper(reader, stream))//This is called for every PAGE of the file
{
for (int pgIndex = 1; pgIndex <= reader.NumberOfPages; pgIndex++)
{
Rectangle pageRectangle = reader.GetPageSizeWithRotation(pgIndex);
PdfContentByte pdfData; //Contains graphics and text content of page returned by pdfstamper
if (this.Dispatcher.Invoke(() => dropdown.Text == "Under Content"))
{
pdfData = pdfStamper.GetUnderContent(pgIndex);
}
else if (this.Dispatcher.Invoke(() => dropdown.Text == "Over Content"))
{
pdfData = pdfStamper.GetOverContent(pgIndex);
}
else//Just in case
{
MessageBox.Show("Something went wrong when adding the watermark");
return;
}
//Set font
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40);
//Create new graphics state and assign opacity
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.25F;
//Set graphics state to pdfcontentbyte
pdfData.SetGState(graphicsState);
//Color of watermark
pdfData.SetColorFill(BaseColor.GRAY);
pdfData.BeginText();
//Show text as per position and rotation
this.Dispatcher.Invoke(() => pdfData.ShowTextAligned(Element.ALIGN_CENTER, WtrmkTextbox.Text, pageRectangle.Width / 2, pageRectangle.Height / 2, 45));
pdfData.EndText();
}
}
}
The error appears on the code for merging, specifically the line " pdf.AddDocument(reader);" BUT I get this error only if I try to add watermarks on more than one files (with just one file it works perfectly).
I'm thinking either I am closing something too early, or addWatermark() does - I've tried changing our the using statemets to no avail. I must be missing something
Okay, it seems PdfStamper was the culprit, i passed the necessary arguements to AddWatermark() and added a simple if statement. Now everything works perfectly.
BIG thanks to Mark Rucker
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; }
}
`
Hi I'm using a ITextSharp to create a PDF. This is my code:
private void FillForm()
{
_path = HttpContext.Current.Server.MapPath("~/") + "\\PDF";
string formFile = _path + "\\Test.pdf";
string newFile = _path + "\\Test2.pdf";
var reader = new PdfReader(formFile);
using (var stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create)))
{
AcroFields fields = stamper.AcroFields;
var conn = new SqlConnection(DataManager.ConnectionString);
conn.Open();
var command = new SqlCommand("SQLCommand"), conn);
var dt = new DataTable();
var adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
int rowIndex = 1;
for (int i=0; i < dt.Rows.Count; i++)
{
var name = (string)dt.Rows[i]["Parameter"];
fields.SetField("txt_" + rowIndex, name);
rowIndex++;
}
stamper.FormFlattening = false;
stamper.Close();
}
}
I have a problem when I'm trying to fill the userName into textboxes. I have a list of names that I get it from the SQL query and I want to display it in different textboxes.
Only the first textBox display its value. For the others I must click on textBox to view the value inside.
Does anyone have any idea how I can fix it?
One line is missing in your code:
fields.GenerateAppearances = true;
You need to add this line right after:
AcroFields fields = stamper.AcroFields;
Why is this happening? Your template is somewhat wrong (maybe it was created using OpenOffice): it says that the software used to fill out the form shouldn't generate the appearances of the fields. As a result the value of the field is added (this is proven by the fact that the text appears when you click it), but the appearance is missing (hence the blank fields).
I have been trying for long but no success i have an existing pdf that i wan to load to my current C# app and want to create a simpe pusbutton to it , plaese cite some working code the default directory of the pdf is "C:\abc.pdf".
I am using itextsharp, C# VS 2010
Thanks
The closest solution I can find is something like the following.
static void AddPushbuttonField(string inputFile, iTextSharp.text.Rectangle buttonPosition, string buttonName, string outputFile)
{
using (PdfStamper stamper = new PdfStamper(new PdfReader(inputFile), File.Create(outputFile)))
{
PushbuttonField buttonField = new PushbuttonField(stamper.Writer, buttonPosition, buttonName);
stamper.AddAnnotation(buttonField.Field, 1);
stamper.Close();
}
}
This came from here, but was not ranked up as a solution. The code looks good and based on my experience with itextsharp I think this will do the trick.
Source:
Adding button in a pdf file using iTextSharp
Rectangle _rect;
_rect = new Rectangle(50, 100, 100, 100);
PushbuttonField button = new PushbuttonField(writer, _rect, "button");
PdfAnnotation widget = button.Field;
button.BackgroundColor = new GrayColor(0.75f);
button.BorderColor = GrayColor.GRAYBLACK;
button.BorderWidth = 1;
button.BorderStyle = PdfBorderDictionary.STYLE_BEVELED;
button.TextColor = GrayColor.GRAYBLACK;
button.FontSize = 11;
button.Text = "Text";
button.Layout = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT;
button.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS;
button.ProportionalIcon = true;
button.IconHorizontalAdjustment = 0;