itextsharp insert text in pdf file with C# - c#

I want to insert text into a pdf file with iTextSharp using the code below. Many times it works right but other times it does not work.
FileStream pdfOutputFile = new FileStream(pdfTemplate, FileMode.Create);
PdfReader pdfReader = new PdfReader(pdffile, System.Text.Encoding.UTF8.GetBytes("ownerPassword"));
PdfStamper pdfStamper = null;
// pdfReader.Permissions = 1;
pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
AcroFields testForm = pdfStamper.AcroFields;
PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(index + 1);
string[] formattext = printTxt.Split(new char[] { '\n' });
float lhight = 0;
float abxt = abx;
printTxt= "Hello word";
ft = new FormattedText(printTxt, Color.Black, "Arial", EncodingType.Winansi, true, 9);
Bitmap b = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(b);
Font f = new Font("Arial", 9);
pdfPageContents.BeginText();
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, "ASCII", false);
pdfPageContents.SetFontAndSize(baseFont,20); // 40 point font
pdfPageContents.SetRGBColorFill(0, 0, 0);
float textAngle = 0;
pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, printTxt, abx+3, (float)aby + 12 + lhight, textAngle);
pdfPageContents.EndText();

The approach I use to write text on any Pdf file is that I create text fields using a software tool PDF Nitro Professional (You can use some other software to create these fields). Once done you can then use the following pattern of code to write text on those fields.
string pdfTemplate = filePath;
string newFile = outputFilePath;
PdfReader PDFWriter = new PdfReader(pdfTemplate);
PdfStamper pdfStampDocument = new PdfStamper(PDFWriter, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStampDocument.AcroFields;
//For Text field
pdfFormFields.SetField("txtTextFieldName", "First Text");
//For Check Box Field
pdfFormFields.SetField("chkSomeCheckBox", "Yes");
PDFWriter.Close();
pdfStampDocument.Close();
Hope it helps.

Related

Add Watermark image to PDF

I'm trying to add watermark to pdf aready exist in a folder inside my project, I'm using iTextSharp.
Everything is going well and debugging the code is going well, but when finished and I try to open the PDF with watermark just worked on, the file is damage.
Here is my piece of code
string sourceFilePath = Server.MapPath(#"~/uploadfiles/PDFFileName.pdf");
byte[] bytes = File.ReadAllBytes(sourceFilePath);
Bitmap bitmap = new Bitmap(200, 30, System.Drawing.Imaging.PixelFormat.Format64bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.White);
graphics.DrawString(text, new System.Drawing.Font("Arial", 12, FontStyle.Bold), new SolidBrush(Color.Red), new PointF(0.4F, 2.4F));
bitmap.Save(Server.MapPath("~/uploadfiles/Image.jpg"), ImageFormat.Jpeg);
bitmap.Dispose();
var img = iTextSharp.text.Image.GetInstance(Server.MapPath("~/uploadfiles/Image.jpg"));
img.SetAbsolutePosition(200, 400);
PdfContentByte waterMark;
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
PdfStamper stamper = new PdfStamper(reader, stream);
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
waterMark = stamper.GetUnderContent(i);
waterMark.AddImage(img);
}
bytes = stream.ToArray();
}
File.Delete(Server.MapPath("~/uploadfiles/Image.jpg"));
File.WriteAllBytes(sourceFilePath, bytes);

I want add digital signature in my dynamic pdf with using itext sharp and in signature insert acrofield

I was trying to insert textfield in digtal signature with using itextsharp but not able to insert that text in esignature.
My code please check Also I want verify that signature still not able to do this code any suggestion would be appriciate..
https://imgur.com/SF11oH1
public void Sign(string SigReason, string SigContact, string SigLocation, bool visible)
{
string password = #"123";
PdfReader reader = new PdfReader(this.inputPDF,new System.Text.ASCIIEncoding().GetBytes(password));
//Activate MultiSignatures
PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true);
//To disable Multi signatures uncomment this line : every new signature will invalidate older ones !
//PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0');
//string pdfTemplate = Server.MapPath("~/Data/PADForm.pdf");
//string newFile = Server.MapPath("~/Data/newFile.pdf");
//signPdfFile(sourceDocument, destinationPath, stream, "123", "testing", "testing");
//PdfReader pdfReader = new PdfReader(pdfTemplate, new System.Text.ASCIIEncoding().GetBytes(password));
//PdfStamper pdfStamper = new PdfStamper(reader, new FileStream(this.outputPDF, FileMode.Create));
string imageURL = #"C:\Users\amitrs\Desktop\FSI SS\204-25.png";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
// Resize image depend upon your need
jpg.ScaleToFit(140f, 120f);
//Give space before image
jpg.SpacingBefore = 10f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_LEFT;
AcroFields pdfFormFields = st.AcroFields;
pdfFormFields.SetField("DigitalSignature", "Amit");
pdfFormFields.SetField("Signature", "Amit Saini");
st.MoreInfo = this.metadata.getMetaData();
st.XmpMetadata = this.metadata.getStreamedMetaData();
PdfSignatureAppearance sap = st.SignatureAppearance;
sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.VERISIGN_SIGNED);
sap.Reason = SigReason;
sap.Contact = SigContact;
sap.Location = SigLocation;
if (visible)
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 300), 1, null);
st.Close();
}
iTextSharp signature appearance object have 2 property, you have to set property.
PdfSignatureAppearance sap = st.SignatureAppearance;
sap.Layer2Text = "XYZ";
Hope this helps

Itextsharp not creating new blank page when loop is at the end of the page

I am opening a pdf template and creating a new pdf and write on it. On the loop I have to enter dynamic data from a list, I am subtracting the height variable to put one item after the other vertically. My issue is that when the list is too long and is approaching the end of the pdf page the code is not creating a new blank page to continue writing the rest items of the list. However, it is overwriting the rest items one above the other in last item of the page. I have try to increase my height variable but still the code is not working to produce new page.
string pdfpath = context.Server.MapPath(#"~/mypdf_new.pdf");
string oldFile = context.Server.MapPath(#"~/mypdftemplate.pdf");
string newFile = pdfpath;
PdfReader reader = new PdfReader(oldFile);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
string myFont = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"Calibri.TTF");
iTextSharp.text.pdf.BaseFont bfR;
bfR = iTextSharp.text.pdf.BaseFont.CreateFont(myFont,
iTextSharp.text.pdf.BaseFont.IDENTITY_H,
iTextSharp.text.pdf.BaseFont.EMBEDDED);
BaseFont title = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
iTextSharp.text.Font titleFont = new iTextSharp.text.Font(title, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
int myheight = 500;
foreach (var mypro in listofproducts)
{
ColumnText ct26 = new ColumnText(cb);
Phrase myText26 = new Phrase(mypro.ProductCode, titleFont);
ct26.SetSimpleColumn(myText26, 60, myheight, 580, 317, 15, Element.ALIGN_LEFT);
ct26.Go();
ColumnText ct28 = new ColumnText(cb);
Phrase myText28 = new Phrase(Convert.ToString(mypro.quantity), titleFont);
ct28.SetSimpleColumn(myText28, 340, myheight, 580, 317, 15, Element.ALIGN_LEFT);
ct28.Go();
myheight = myheight - 20;
}
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
document.Close();
fs.Close();
writer.Close();
reader.Close();

itextsharp adding image to existing pdf

i am trying to add an image using itextsharp but not having any luck
there are a ton of tutorials for adding an image to a new pdf doc but not and existing pdf so the .add menthod is not avaivlable
i am tring to do use the stamper write method to add image
and i dont get any errors but no image shows up
PdfReader reader = new PdfReader(pdfIn); //get pdf
if (File.Exists(pdfOut)) File.Delete(pdfOut); //reset
FileStream fs = new FileStream(pdfOut, FileMode.Create);
PdfStamper stamper = new PdfStamper(reader, fs);
try
{
// Convert base64string to bytes array
Byte[] bytes = Convert.FromBase64String(base64decode);
iTextSharp.text.Image sigimage = iTextSharp.text.Image.GetInstance(bytes);//
sigimage.SetAbsolutePosition(10, 10);
sigimage.ScaleToFit(140f, 120f);
stamper.Writer.Add(sigimage);
}catch (DocumentException dex){//log exception here
}catch (IOException ioex){//log exception here
}
AcroFields fields = stamper.AcroFields;
//repeat for each pdf form fill field
fields.SetField("agencyName", name.Value);
stamper.FormFlattening = true; // set to true to lock pdf from being editable
stamper.Writer.CloseStream = true;
stamper.Close();
reader.Close();
fs.Close();
I think you try the following adding it to bytes
PdfReader reader = new PdfReader(pdfIn)
FileStream fs = new FileStream(pdfOut, FileMode.Create);
var stamper = new PdfStamper(reader, fs);
var pdfContentByte = stamper.GetOverContent(1);
iTextSharp.text.Image sigimage = iTextSharp.text.Image.GetInstance(bytes);
sigimage.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(sigimage);
using following code you can able to add image to each page in an existing pdf file. ( I use this code for desktop application)
string FileLocation = #"C:\\test\\pdfFileName.pdf"; // file path of pdf file
var uri = new Uri(#"pack://application:,,,/projrct_name;component/View/Icons/funnelGreen.png"); // use image from project/application folder (this image will insert to pdf)
var resourceStream = Application.GetResourceStream(uri).Stream;
PdfReader pdfReader = new PdfReader(FileLocation);
PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf", "(tempFile).pdf"), FileMode.Create));iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(resourceStream), System.Drawing.Imaging.ImageFormat.Png);
img.SetAbsolutePosition(125, 350); // set the position in the document where you want the watermark to appear.
img.ScalePercent(35f);// not neccessory, use if you want to adjust image
img.ScaleToFit(140f, 100f); // not neccessory, use if you want to adjust image
PdfContentByte waterMark;
for (int page = 1; page <= pdfReader.NumberOfPages; page++) // for loop will add image to each page. Based on the condition you can add image to single page also
{
waterMark = stamp.GetOverContent(page);
waterMark.AddImage(img);
}
stamp.FormFlattening = true;
stamp.Close();// closing the pdfStamper, the order of closing must be important
pdfReader.Close();
File.Delete(FileLocation);
File.Move(FileLocation.Replace(".pdf", "(tempFile).pdf"), FileLocation);

Adding text in the pdf using itextsharp

I am trying to create a pdf with pdf stamper which is working fine. I have created a big multiline textbox in the template, where I need to print a huge string. To the string I need to make few string in bold and other in normal font. I tried in many ways, but could not get the font in bold.I need to make the Heading string in bold.
string pdfTemplatePath = Server.MapPath("PDF/" + group + "/template.pdf");
PdfReader pdfReader = new PdfReader(pdfTemplatePath);
MemoryStream myMemoryStream = new MemoryStream();
PdfStamper pdfStamper = new PdfStamper(pdfReader, myMemoryStream);
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("Name", "abc");
string a = "Some text";
string b = "Some large text";
StringBuilder sb = new StringBuilder();
sb.Append("Heading1");
sb.Append(a);
sb.Append("Heading2");
sb.Append(b);
String htmlText = sb.ToString();
List<IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlText), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
phrase.Add((IElement)htmlarraylist[k]);
}

Categories