1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
using iTextSharp.text; using iTextSharp.text.pdf; namespace pdfgenerator { class Program { static void Main(string[] args) { // Create a new document Document doc = new Document(PageSize.A4, 10, 10, 10, 10); // Create a PdfWriter object PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("output.pdf", FileMode.Create)); // Open the document doc.Open(); // Get all the image files from the folder string[] jpgFiles = Directory.GetFiles("images", "*.jpg"); string[] pngFiles = Directory.GetFiles("images", "*.png"); string[] allFiles = jpgFiles.Concat(pngFiles).ToArray(); foreach (var file in allFiles) { // Create a new image object Image img = Image.GetInstance(file); // Calculate the scale factor to fit the image to the page float docWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin; float docHeight = doc.PageSize.Height - doc.TopMargin - doc.BottomMargin; float imgWidth = img.ScaledWidth; float imgHeight = img.ScaledHeight; float scaleFactor = Math.Min(docWidth / imgWidth, docHeight / imgHeight); img.ScalePercent(scaleFactor * 100); // Add a new page for each image doc.NewPage(); doc.Add(img); } // Close the document doc.Close(); } } } |