Tuesday, June 29, 2010

iTextSharp - read an existing pdf, resize it and then draw it on a new one


PdfReader reader = new PdfReader("In.PDF");
Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
PdfWriter writer = PdfWriter.GetInstance(doc, 
new FileStream("Out.PDF",
FileMode.Create));
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page = writer.GetImportedPage(reader, 1); //page #1
float Scale = 0.67f;
cb.AddTemplate(page, Scale, 0, 0, Scale, 0, 0);
doc.Close();

Friday, June 11, 2010

Add an image at a given position without fail on any page of a pdf file.

Looking for a way to add an image at a given position on a pdf ( Provided you use iTextSharp for .Net library). Here is the way to go.


Following code is an extract from here.


string pdfTemplate = @"c:\Temp\PDF\fw4.pdf";
string newFile = @"c:\Temp\PDF\completed_fw4.pdf";


PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
string chartLoc = string.Empty;
chartLoc = @"C:\Temp\PDF\IMG_3746.jpg";//pplLogoSmall.jpg";


iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(chartLoc);
iTextSharp.text.pdf.PdfContentByte overContent;


iTextSharp.text.Rectangle rect;
try
{
Single X, Y;int pageCount = 0;
rect = pdfReader.GetPageSizeWithRotation(1);
if (chartImg.Width > rect.Width || chartImg.Height > rect.Height)
{
chartImg.ScaleToFit(rect.Width, rect.Height);
X = (rect.Width - chartImg.ScaledWidth) / 2;
Y = (rect.Height - chartImg.ScaledHeight) / 2;
}
else
{
X = (rect.Width - chartImg.Width) / 2;
Y = (rect.Height - chartImg.Height) / 2;
}
chartImg.SetAbsolutePosition(X, Y);
pageCount = pdfReader.NumberOfPages;
for (int i = 1; i < pageCount; i++)
{
overContent = pdfStamper.GetOverContent(i);
overContent.AddImage(chartImg);
}
pdfStamper.Close();
pdfReader.Close();
}
catch (Exception ex)
{
throw ex;
}

Happy Coding!