///
/// Convert Image to PDF
///
/// Image Path
/// Output PDF Path
/// Image Width
/// Image Height
/// Output PDF Path
private String ImageToPdf(String sImgPath, String sOutputPath, float imgW, float imgH)
{
Bitmap bm = null;
iTextSharp.text.Document objiTxtdoc = null;
iTextSharp.text.pdf.PdfWriter objiTextWriter = null;
iTextSharp.text.pdf.PdfContentByte objiTextCntbyt = null;
iTextSharp.text.Image objiTextImg = null;
int iTotal;
iTextSharp.text.Rectangle objPazeSize;
float fPDFPageWidth=8.0;
float fPDFPageHeight=10.0;
try
{
objPazeSize = new iTextSharp.text.Rectangle(0, 0, fPDFPageWidth,fPDFPageHeight);
//Get new Document object for Page
objiTxtdoc = new iTextSharp.text.Document(objPazeSize, 0, 0, 0, 0);
// creation of the different writers
objiTextWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(objiTxtdoc, new System.IO.FileStream(sOutputPath, System.IO.FileMode.Create));
//Load the tiff image and count the total pages
bm = new Bitmap(sImgPath);
//Get Total Page
iTotal = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
objiTxtdoc.Open();
objiTextWriter.SetLinearPageMode();
objiTextWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_4);
objiTextCntbyt = objiTextWriter.DirectContent;
for (int k = 0; k < iTotal; ++k)
{
bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
objiTextImg = iTextSharp.text.Image.GetInstance(bm, iTextSharp.text.BaseColor.BLACK, true);
//Scale Image to fit in the page
float flXper = (objPazeSize.Width / imgW) * 100;
float flYper = (objPazeSize.Height / imgH) * 100;
objiTextImg.ScalePercent(flXper, flYper);
objiTextImg.SetAbsolutePosition(0, 0);
//add Image on Page
objiTextCntbyt.AddImage(objiTextImg);
objiTxtdoc.NewPage();
}
return sOutputPath;
}
catch (Exception ex)
{
m_objCommon.WriteLog("Form1", "ImageToPdf", m_sErrorLogFilePath, ex);
return null;
}
finally
{
bm.Dispose();
objiTxtdoc.Close();
objiTextWriter.Close();
objiTextCntbyt.ClosePath();
GC.Collect();
}
}
No comments:
Post a Comment