Pages

Tuesday, 10 May 2011

Creating Barcode image in PDF Document in ASP.NET using iTextsharp dll file


Add the following headers to aspx page

using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;


The following method will create a barcode image

public void CreateBarCode()
{
Document
doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, new FileStream(path, FileMode.CreateNew));
doc.Open();

System.IO.MemoryStream mem = new MemoryStream();
 Barcode128 barImg = new Barcode128();
barImg.Code = "TRISHANK";
barImg.CreateDrawingImage(System.Drawing.iTextSharp.text.Color.Black, System.Drawing.Color.White).Save(mem, System.Drawing.Imaging.ImageFormat.Png);

Image imgs = iTextSharp.text.Image.GetInstance(mem.ToArray());
mem.Flush();
mem.Close();
doc.Add(imgs);

doc.Close();
}


Output :

Add Watermark to PDF document in ASP.NET using iTextsharp dll file

The following code will add watermark text to pdf document

You need to add the following headers to your aspx page

using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;


The following method will add watermark text


public  static byte[] WriteToPdf(FileInfo sourceFile, string stringToWriteToPdf)
{
PdfReader reader = new PdfReader(sourceFile.FullName);

using (MemoryStream memoryStream = new MemoryStream())
{
PdfStamper pdfStamper = new PdfStamper(reader, memoryStream);

for (int i = 1; i <= reader.NumberOfPages; i++)
{
Rectangle pageSize = reader.GetPageSizeWithRotation(i);

PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(i);
pdfPageContents.BeginText();

BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false);
pdfPageContents.SetFontAndSize(baseFont,80);
pdfPageContents.SetRGBColorFill(137, 142, 136);

float textAngle =(float) GetHypotenuseAngleInDegreesFrom(pageSize.Height, pageSize.Width);
pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, stringToWriteToPdf, pageSize.Width/2, pageSize.Height/2, textAngle);
pdfPageContents.EndText();
}
pdfStamper.FormFlattening = true;
pdfStamper.Close();
reader.Close();
return memoryStream.ToArray();
}
}

The following method will set the angle for the watermark text

public static double GetHypotenuseAngleInDegreesFrom(double opposite, double adjacent)
{
double radians = Math.Atan2(opposite, adjacent);
double angle = radians*(180/Math.PI);
return angle;
}


Output :