3
Answers

Convert Multiple Images to PDF using iTextSharp?

honar abubakr

honar abubakr

8y
6.4k
1
Hello friends, in my small project i have a button for converting more than one image file to pdf, i made some search in google and found some articles about that i found one that helps me to do that but convert only two images to pdf, and i want to make it unspecified number of image to pdf
 
this is my code:
private void button2_Click(object sender, EventArgs e)
{
string sMergedFiles = @"C:\PDFTest\PdfReport.PDF";\\pdf file path

string sTiffFiles = "C:\\PDFTest\\TiffFiles\\";\\Tiff image files path

Document document = new Document(PageSize.A4, 50, 50, 50, 50);

PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(sMergedFiles, FileMode.CreateNew));

document.Open();

//here you can loop thru and call AddTiff2Pdf for multiple files

string tiffFileName = Path.Combine(sTiffFiles, "asdf.tif");\\first tiff image

AddTiff2Pdf(tiffFileName, ref writer, ref document);

tiffFileName = Path.Combine(sTiffFiles, "1234.tif");\\second tiff image

AddTiff2Pdf(tiffFileName, ref writer, ref document);

document.Close();
}
private void AddTiff2Pdf(string tiffFileName, ref PdfWriter writer, ref Document document)
{

Bitmap bitmap = new Bitmap(tiffFileName);

int numberOfPages = bitmap.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

PdfContentByte cb = writer.DirectContent;

for (int page = 0; page < numberOfPages; page++)
{

bitmap.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, page);

System.IO.MemoryStream stream = new System.IO.MemoryStream();

bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(stream.ToArray());

stream.Close();

img.ScalePercent(72f / bitmap.HorizontalResolution * 100);

img.SetAbsolutePosition(0, 0);

cb.AddImage(img);

document.NewPage();
}
}
can anyone help me please? how to do that
Answers (3)