PNG 图片转PDF
安装依赖包
iTextSharp-LGPL-Core(1.2.0)
#region iTextSharp 合并多个PDF
/// <param name="SourcePath">源路径</param>
/// <param name="TargetPath">目标路径</param>
/// <param name="NewFileName">新文件名</param>
public static void MergePDF(string SourcePath, string TargetPath, string NewFileName)
{
//需要合并的pdf集合
string[] fileList = Directory.GetFiles(SourcePath, "*.pdf", SearchOption.AllDirectories);
//合并到的总PDF
string outMergeFile = TargetPath + "\\" + NewFileName;
PdfReader reader;
iTextSharp.text.Document document = new iTextSharp.text.Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage newPage;
for (int i = 0; i < fileList.Length; i++)
{
reader = new PdfReader(fileList[i]);
int iPageNum = reader.NumberOfPages;
for (int j = 1; j <= iPageNum; j++)
{
document.NewPage();
newPage = writer.GetImportedPage(reader, j);
cb.AddTemplate(newPage, 0, 0);
}
}
document.Close();
}
#endregion
/// <summary>
/// iTextSharp 图片合并成pdf
/// </summary>
/// <param name="files">List Png</param>
/// <param name="pdfFileName">pdf 文件路径</param>
/// <returns></returns>
public bool MergeFileToPDF(List<string> files, string pdfFileName)
{
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);
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 - 25)
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
}
else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25)
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
}
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;
}