多图转PDF工具,效果如下:
功能
- 支持多张图片;
- 支持转前对图片排序;
- 支持插入新图片;
- 支持删除已有图片;
- 当宽度大于高度时自动旋转图片;
- 以A4纸规格生成PDF
用法:标题
复制以下代码新建一个winform项目即可运行,或联系我获取软件31705252@qq.com。
代码如下:
public partial class form1 : Form
{
//1.创建数据源
static DataTable dataSource = new DataTable("pdf");
public form1()
{
InitializeComponent();
//是否显示最后一列的新行
dataGridView1.AllowUserToAddRows = false;
//不允许多行或多列选择
dataGridView1.MultiSelect = false;
//初始数据源结构
dataSource.Columns.Add("fn", typeof(String));
dataSource.Columns.Add("dt", typeof(DateTime));
}
/// <summary>
/// 选择文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSleImgFolder_Click(object sender, EventArgs e)
{
if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
if (this.folderBrowserDialog1.SelectedPath.Trim() != "")
this.txtImgFolder.Text = this.folderBrowserDialog1.SelectedPath.Trim();
DirectoryInfo difs = new DirectoryInfo(txtImgFolder.Text);//根据当前路径创建一个对象
FileInfo[] array = difs.GetFiles("*.*");//获取当前文件甲下的所有文件名
if(array==null || array.Length == 0)
{
MessageBox.Show($"未发现可用的图片", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
dataSource.Clear();
//int index = 1;
foreach (FileInfo file in array)
{
//dt.Rows.Add(index++, file.Name , file.CreationTime);
dataSource.Rows.Add(this.folderBrowserDialog1.SelectedPath.Trim() +
}
dataGridView1.DataSource = dataSource;
}
}
/// <summary>
/// 开始生成pdf
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreatePDF_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(txtPdfName.Text))
{
txtPdfName.Focus();
MessageBox.Show($"请填写PDF文件名称", "错误提示",MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
iTextSharpCreatPDF(dataSource);
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
//上
DataRowCollection rows = dataSource.Rows;
if (e.RowIndex > 0)
{
DataRow row = rows[e.RowIndex];
string fn = row["fn"]?.ToString();
string dt = row["dt"]?.ToString();
rows.RemoveAt(e.RowIndex);
DataRow newRow= dataSource.NewRow();
newRow.ItemArray= new object[] { fn, dt };
rows.InsertAt(newRow, e.RowIndex - 1);
}
}
else if (e.ColumnIndex == 1)
{
//下
DataRowCollection rows = dataSource.Rows;
int newIndex = e.RowIndex + 1;
if (newIndex < rows.Count)
{
DataRow row = rows[e.RowIndex];
string fn = row["fn"]?.ToString();
string dt = row["dt"]?.ToString();
rows.RemoveAt(e.RowIndex);
DataRow newRow = dataSource.NewRow();
newRow.ItemArray = new object[] { fn, dt };
rows.InsertAt(newRow, newIndex);
}
}
else if (e.ColumnIndex == 2)
{
//加
openFileDialog1.Filter = "图片|*.bmp;*.gif;*.jpeg;*.jpg;*.png";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK) {
DataTable dt = dataSource;// tble as DataTable;
string [] files=this.openFileDialog1.FileNames;
int addIndex = e.RowIndex;
foreach (string path in files) {
FileInfo file = new FileInfo(path);
DataRow row = dt.NewRow();
row.ItemArray = new object[] { path, file.CreationTime };
dt.Rows.InsertAt(row, ++addIndex);
}
}
}
else if (e.ColumnIndex == 3)
{
//删
object tble = dataGridView1.DataSource;
DataTable files = tble as DataTable;
files.Rows.RemoveAt(e.RowIndex);
//dataGridView1.DataSource = files;
}
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridViewRowCollection rows = dataGridView1.Rows;
int index = 1;
foreach (DataGridViewRow row in rows) {
row.HeaderCell.Value = ( index++).ToString();
}
dataGridView1.Refresh();
}
public void iTextSharpCreatPDF(DataTable files)
{
Document doc = new Document(pageSize:PageSize.A4,0,0,0,0);
try
{
PdfWriter.GetInstance(doc, new FileStream($@"d:\{txtPdfName.Text}.pdf", FileMode.Create));
doc.Open();
foreach (DataRow row in files.Rows)
{
string file =row["fn"].ToString();
//下面对图片进行操作
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(file);
image.ScaleAbsolute(PageSize.A4);// '设置图片大小为A4纸大小
image = AddImage(image, 1, 0, 0);
doc.Add(image);
}
}
catch (DocumentException dex)
{
MessageBox.Show(dex.Message);
}
finally
{
doc.Close();
MessageBox.Show($"已生成{txtPdfName.Text}.pdf,请到D盘查看", "已生成PDF", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
/// 设置图片大小
/// <param name="Alignment">对齐方式 (0/1/2)</param>
/// <param name="marginRight">页边距</param>
/// <param name="marginBottom">页边距</param>
/// </summary>
public static iTextSharp.text.Image AddImage(iTextSharp.text.Image img, int Alignment, float marginRight, float marginBottom)
{
//iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(new Uri(path));
img.Alignment = Alignment;
//等比缩放,宽与高的缩放系数哪个大就取哪一个(比如高的系数是0.8,宽的是0.7,则取0.7。这样图片就不会超出页面范围)
if (img.Width > img.Height)
{
//这里计算图片的缩放系数,因为图片width>height,所以将图片旋转90度以适应页面,计算缩放系数的时候宽与高对调
float PageHeight = PageSize.A4.Height - marginBottom * 3;
double percentHeight = Math.Round((PageHeight / img.Width), 2);
float PageWidth = PageSize.A4.Width - marginRight * 2;
double percentWidth = Math.Round((PageWidth / img.Height), 2);
double percent = percentHeight > percentWidth ? percentWidth : percentHeight;
img.ScalePercent((float)percent * 100);
img.RotationDegrees = 90f;
}
else
{
float PageHeight = PageSize.A4.Height - marginBottom * 3;
double percentHeight = Math.Round((PageHeight / img.Height), 2);
float PageWidth = PageSize.A4.Width - marginRight * 2;
double percentWidth = Math.Round((PageWidth / img.Width), 2);
double percent = percentHeight > percentWidth ? percentWidth : percentHeight;
img.ScalePercent((float)percent * 100);
}
return img;
}
}