PDF文档转换为图片、图片转成PDF 及PDF合并

2023-06-08,,

简介

功能:PDF文档按每页转换成一张图片,一张图片转换成一张PDF 并将多张PDF合成一个多页的PDF文档。

经历:在各个网站上搜索始终出现各种问题,尤其是遇到引用的版本问题尤其头疼,不是不能适用当前的方法就是出现水印标签,最终在各位大佬的帮助下终于完成一个相对完整的代码(主要的是能满足需求)。

背景

之前在项目中遇到一个需求:将多页的PDF上传并转成图片展示要求一页一页的排列开看(例如图1),并要求在传送到服务中心平台看到的时候是PDF文档(服务中心平台只提供下载)。

点击下载需要使用到的dll文件

O2S.Components.PDFRender4NET.dll 版本:4.7.4.0

itextsharp.dll 版本:5.5.10.0

主要的代码如下

        /// <summary>
/// 将PDF文档转换为图片的方法
/// </summary>
/// <param name="pdfInputPath"></param>
/// <param name="desPath">输出相对路径</param>
/// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
/// <returns></returns>
public static List<string> ConvertPDF2Image(string pdfInputPath, string desPath, Definition definition, string title)
{
List<string> imgList = new List<string>();
PDFFile pdfFile = PDFFile.Open(pdfInputPath);
int startPageNum = , endPageNum = pdfFile.PageCount;
int number = ;
for (int i = startPageNum; i <= endPageNum; i++)
{
Bitmap pageImage = pdfFile.GetPageImage(i - , * (int)definition);
string filePath = desPath + title + "-" + number + ".jpg";
imgList.Add(filePath);
pageImage.Save(System.Web.HttpContext.Current.Server.MapPath(filePath));
number++;
}
pdfFile.Dispose();
return imgList;
} public enum Definition
{
One = , Two = , Three = , Four = , Five = , Six = , Seven = , Eight = , Nine = , Ten =
} /// <summary>
/// 合并PDF
/// </summary>
/// <param name="fileList">绝对路径集合</param>
/// <param name="outMergeFile">合并后的文件存在地址绝对路径</param>
public static void mergePdfFiles(List<string> fileList, string outMergeFile)
{
PdfReader reader;
//此处将内容从文本提取至文件流中的目的是避免文件被占用,无法删除
FileStream fs1 = new FileStream(fileList[], FileMode.Open);
byte[] bytes1 = new byte[(int)fs1.Length];
fs1.Read(bytes1, , bytes1.Length);
fs1.Close();
reader = new PdfReader(bytes1);
reader.GetPageSize();
// iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(1000,800);//设置样式
iTextSharp.text.Rectangle rec = reader.GetPageSize();
float width = rec.Width;
float height = rec.Height;
//创建一个文档变量
iTextSharp.text.Document document = new iTextSharp.text.Document(rec, , , , );
//创建该文档
PdfWriter pdfWrite = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
//打开文档
document.Open();
//添加内容
PdfContentByte contentByte = pdfWrite.DirectContent;
PdfImportedPage newPage;
for (int i = ; i < fileList.Count; i++)
{ FileStream fs = new FileStream(fileList[i], FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, , bytes.Length);
fs.Close();
reader = new PdfReader(bytes);
int pageNum = reader.NumberOfPages;//获取文档页数
for (int j = ; j <= pageNum; j++)
{
document.NewPage();
newPage = pdfWrite.GetImportedPage(reader, j);
contentByte.AddTemplate(newPage, , );
} }
document.Close();
}
        /// <summary>
/// 图片转PDF
/// </summary>
/// <param name="imagepath">图片位置(绝地路径)</param>
/// <param name="pdfpath">存放PDF地址(绝地路径)</param>
public static void iTextSharpCreatPDF(string imagepath, string pdfpath)
{
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
float percentage = ;
//这里都是图片最原始的宽度与高度
float resizedWidht = image.Width;
float resizedHeight = image.Height;
Document doc = new Document(new iTextSharp.text.Rectangle(resizedWidht, resizedHeight), , , , ); //new Rectangle(1000,1000) //指定文件预设开档时的缩放为100%
//PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
try
{
PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));
doc.Open();
#region 下面对图片进行操作
////这时判断图片宽度是否大于页面宽度减去也边距,如果是,那么缩小,如果还大,继续缩小,
////这样这个缩小的百分比percentage会越来越小
while (resizedWidht > (doc.PageSize.Width - doc.LeftMargin - doc.RightMargin))
{
percentage = percentage * 0.9f;
resizedHeight = image.Height * percentage;
resizedWidht = image.Width * percentage;
}
#region 注释
////There is a 0.8 here. If the height of the image is too close to the page size height,
////the image will seem so big
//while (resizedHeight > (doc.PageSize.Height - doc.TopMargin - doc.BottomMargin) * 0.8)
//{
// percentage = percentage * 0.9f;
// resizedHeight = image.Height * percentage;
// resizedWidht = image.Width * percentage;
//}
#endregion
////这里用计算出来的百分比来缩小图片
image.ScalePercent(percentage * );
//让图片的中心点与页面的中心点进行重合
image.SetAbsolutePosition(doc.PageSize.Width / - resizedWidht / , doc.PageSize.Height / - resizedHeight / );
doc.Add(image);
#endregion
}
catch (DocumentException dex)
{
System.Web.HttpContext.Current.Response.Write(dex.Message);
}
catch (IOException ioex)
{
System.Web.HttpContext.Current.Response.Write(ioex.Message);
} catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
finally
{
doc.Close();
}
}

PDF文档转换为图片、图片转成PDF 及PDF合并的相关教程结束。

《PDF文档转换为图片、图片转成PDF 及PDF合并.doc》

下载本文的Word格式文档,以方便收藏与打印。