把上传过来的多张图片拼接转为PDF的实现代码

2023-05-25,,

以下是把上传过来的多张图片拼接转为PDF的实现代码,不在本地存储上传上来的图片,下面是2中做法,推荐第一种,把pdf直接存储到DB中比较安全。

如果需要在服务器上存储客户端上传的文件时,切记存储文件时不能使用客户端传入的任意参数,否则可能存在安全隐患,比如客户端传入参数filetype, 如果程序使用了这个参数并作为了上传文件的保存路径的某个文件夹时,就会有安全隐患,如客户使用..\..\filetype当做filetype的值传入后台时,就会在server端创建对应的文件夹,就会使得服务器的文件系统被客户控制了,切记此点。

//把上传上来的多张图片直接转为pdf,并返回pdf的二进制,但不存储图片
public static byte[] generatePDF2(HttpFileCollection hfc)
{
Document document = new Document();
var ms = new MemoryStream();
PdfWriter.GetInstance(document, ms);
document.Open(); //输出图片到PDF文件
var extensionList = ".jpg, .png, .jpeg, .gif, .bmp";
float height = ;
for (int i = ; i < hfc.Count; i++)
{
if (hfc[i] != null && extensionList.Contains(Path.GetExtension(hfc[i].FileName).ToLower()))
{
var imgBytes = StreamToBytes(hfc[i].InputStream);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imgBytes);
float percentage = ;
//这里都是图片最原始的宽度与高度
float resizedWidht = image.Width;
float resizedHeight = image.Height; //这时判断图片宽度是否大于页面宽度减去也边距,如果是,那么缩小,如果还大,继续缩小,
//这样这个缩小的百分比percentage会越来越小
while (resizedWidht > (document.PageSize.Width - document.LeftMargin - document.RightMargin) * 0.8)
{
percentage = percentage * 0.9f;
resizedHeight = image.Height * percentage;
resizedWidht = image.Width * percentage;
}
//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 > (document.PageSize.Height - document.TopMargin - document.BottomMargin) * 0.8)
{
percentage = percentage * 0.9f;
resizedHeight = image.Height * percentage;
resizedWidht = image.Width * percentage;
} ////这里用计算出来的百分比来缩小图片
image.ScalePercent(percentage * );
//让图片的中心点与页面的中心店进行重合
//image.SetAbsolutePosition(document.PageSize.Width / 2 - resizedWidht / 2, height + 10);
image.Alignment = Image.MIDDLE_ALIGN;
document.Add(image); height += resizedHeight;
}
}
if (document.IsOpen())
document.Close(); return ms.ToArray();
}
/// <summary>
/// 把指定文件夹的所有图片拼接到pfd中,并保存上传图片到server
/// </summary>
/// <param name="imgFilePath">需要拼接的图片所在的文件夹的绝对路径</param>
/// <param name="pdfPath">需要生成的pdf的绝对路径,包括文件</param>
public static bool generatePDF(string imgFilePath, string pdfPath)
{
var flag = false;
if (!string.IsNullOrWhiteSpace(imgFilePath) && !string.IsNullOrWhiteSpace(pdfPath) && Directory.Exists(imgFilePath))
{
Document document = new Document();
var pdfDirectory = Path.GetDirectoryName(pdfPath);
if (!Directory.Exists(pdfDirectory))
{
Directory.CreateDirectory(pdfDirectory);
} PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create));
document.Open(); //输出图片到PDF文件
var extensionList = ".jpg, .png, .jpeg, .gif, .bmp";
var fileList = Directory.GetFiles(imgFilePath);
if (fileList != null && fileList.Any())
{
float height = ;
foreach (var file in fileList)
{
if (extensionList.Contains(Path.GetExtension(file).ToLower()))
{
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(file);
float percentage = ;
//这里都是图片最原始的宽度与高度
float resizedWidht = image.Width;
float resizedHeight = image.Height; //这时判断图片宽度是否大于页面宽度减去也边距,如果是,那么缩小,如果还大,继续缩小,
//这样这个缩小的百分比percentage会越来越小
while (resizedWidht > (document.PageSize.Width - document.LeftMargin - document.RightMargin) * 0.8)
{
percentage = percentage * 0.9f;
resizedHeight = image.Height * percentage;
resizedWidht = image.Width * percentage;
}
//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 > (document.PageSize.Height - document.TopMargin - document.BottomMargin) * 0.8)
{
percentage = percentage * 0.9f;
resizedHeight = image.Height * percentage;
resizedWidht = image.Width * percentage;
} ////这里用计算出来的百分比来缩小图片
image.ScalePercent(percentage * );
//让图片的中心点与页面的中心店进行重合
//image.SetAbsolutePosition(document.PageSize.Width / 2 - resizedWidht / 2, height + 10);
image.Alignment = Image.MIDDLE_ALIGN;
document.Add(image); height += resizedHeight;
}
}
if (document.IsOpen())
document.Close();
flag = true;
}
}
return flag;
}

调用如下:

private byte[] generatePDF2(HttpFileCollection hfc, int fileType)
{
byte[] bytes = null;
if (hfc != null && hfc.Count > )
{
//上传文件是图片类型
if (fileType == )
{
bytes = FileUtility.generatePDF2(hfc);
}
//fileType == 2 上传文件是pdf文件类型
else if (fileType == && hfc[] != null)
{
bytes = FileUtility.StreamToBytes(hfc[].InputStream);
}
}
return bytes;
} public static byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, , bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(, SeekOrigin.Begin);
return bytes;
} //客户端使用$.ajaxFileUpload插件上传文件
public ActionResult FilesUpload()
{
bool result = true; NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form;
HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
string fileType = nvc.Get("FileType"); //上传文件都是图片就调用生成pdf文件,把上传图片拼接到pdf
//如果上传文件是pdf文件,则直接存起来即可
bytes = generatePDF2(hfc, uploadFileType);
} function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: 'UserController/FilesUploadToServer', //用于文件上传的服务器端请求地址
type: 'Post',
data: {
FileName: $("#txtFileName").val(),
PageCount: $("#txtPageCount").val(),
SignDate: $("#txtSignDate").val(),
FileType: $("#selFileType").val(),
IsPermanent: $("#chkIsPermanent").is(":checked") ? :
},
secureuri: false, //一般设置为false
fileElementId: 'uploadFile', //文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'json', //返回值类型 一般设置为json
//async: false,
success: function (data, status) //服务器成功响应处理函数
{
showUploadImgs(data);
if (data.msg && data.msg != '') {
bootbox.alert(data.msg, function () {
bindFileEvent();
if (data.result)
location.reload();
});
}
},
error: function (data, status, e)//服务器响应失败处理函数
{
if (e && e.message && e.message.indexOf('Unexpected token') >= ) {
bootbox.alert(e.message);
//location.href = '/Account/Login';
window.location.reload();
}
else {
bootbox.alert(e.message);
$("#loading").hide();
$(this).removeAttr("disalbed");
}
}
}
)
return false;
}

把上传过来的多张图片拼接转为PDF的实现代码的相关教程结束。

《把上传过来的多张图片拼接转为PDF的实现代码.doc》

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