C#把图片合并生成新的PDF

需要安装 iTextSharp

string[] picFileNames = Directory.GetFiles(imgsourcePath, “*”);
List<string> fileNames = picFileNames.ToList();
string new_szFileName = sourcePath + “b\\”;

if (!Directory.Exists(new_szFileName))
{
Directory.CreateDirectory(new_szFileName);
}
new_szFileName = new_szFileName + “b.pdf”; //新的PDF

MergeFileToPDF(fileNames, new_szFileName);

 

/// <summary>
///
/// </summary>
/// <param name=”files”>图片路径</param>
/// <param name=”pdfFileName”>存储pdf路径</param>
/// <returns></returns>
public static bool MergeFileToPDF(List<string> files, string pdfFileName)
{
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
try
{
iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(pdfFileName, FileMode.Create, FileAccess.ReadWrite));
document.Open();
iTextSharp.text.Image image;
foreach (var item in files)
{

if (String.IsNullOrEmpty(item)) break;
image = iTextSharp.text.Image.GetInstance(item);
//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.SetAbsolutePosition((iTextSharp.text.PageSize.A4.Width – image.ScaledWidth)/2 + 10, (iTextSharp.text.PageSize.A4.Height – image.ScaledHeight)/2);
//}
image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
//document.NewPage();//解开注释默认一张图片占一页,注释自动撑满后自动下一页
document.Add(image);
}
document.Close();
return true;
}
catch (Exception ex)
{
Console.WriteLine(“转换失败,原因:” + ex.Message);
}
return false;

}

来源地址:C#把图片合并生成新的PDF

转载声明:本站文章若无特别说明,皆为原创,转载请注明来源:www.88531.cn资享网,谢谢!^^

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享