using iTextSharp.text; using iTextSharp.text.pdf; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace JGP2PDF { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { OpenFileDialog op = new OpenFileDialog(); op.Multiselect = true; op.Filter = "标签 | *.jpg"; if (op.ShowDialog() == DialogResult.OK) { var filenames = op.FileNames; ConvertJPG2PDF(filenames, textBox2.Text); MessageBox.Show("导出成功!"); } } catch (Exception ex) { MessageBox.Show(ex.Message); throw ex; } } private static void ConvertJPG2PDF(string[] jpgfiles, string pdf) { var document = new Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0); using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None)) { PdfWriter.GetInstance(document, stream); document.Open(); foreach (var jpgfile in jpgfiles) { using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var image = iTextSharp.text.Image.GetInstance(imageStream); if (image.Height > iTextSharp.text.PageSize.A4.Height) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height); } else if (image.Width > iTextSharp.text.PageSize.A4.Width) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height); } image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.Add(image); } } document.Close(); } } } }