以下是把上传过来的多张图片拼接转为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的实现代码的更多相关文章

  1. Android仿微信图片上传,可以选择多张图片,缩放预览,拍照上传等

    仿照微信,朋友圈分享图片功能 .可以进行图片的多张选择,拍照添加图片,以及进行图片的预览,预览时可以进行缩放,并且可以删除选中状态的图片 .很不错的源码,大家有需要可以下载看看 . 微信 微信 微信 ...

  2. angular+ckeditor最后上传的最后一张图片不会被添加(bug)

    做法一: angularJs+ckeditor 一.页面 <textarea ckeditor required name="topicContent" ng-model=& ...

  3. Android图片上传,可以选择多张图片,缩放预览,拍照上传等

    仿照微信,朋友圈分享图片功能 .可以进行图片的多张选择,拍照添加图片,以及进行图片的预览,预览时可以进行缩放,并且可以删除选中状态的图片 .很不错的源码,大家有需要可以下载看看 . 微信 微信 微信 ...

  4. 微信小程序上传一或多张图片

    一.要点 1.选取图片 wx.chooseImage({ sizeType: [], // original 原图,compressed 压缩图,默认二者都有 sourceType: [], // a ...

  5. PHP结合Ueditor并修改图片上传路径 微信小程序 拼接域名显示图片

    前言 在使用UEditor编辑器时,一般我们都是需要修改默认的图片上传路径的,下面是我整理好的修改位置和方法供大家参考. 操作 Ueditor PHP版本本身自带了一套上传程序,我们可以在此基础中,找 ...

  6. H5利用formData来上传文件(包括图片,doc,pdf等各种格式)方法小结!

    H5页面中我们常需要进行文件上传,那么怎么来实现这个功能呢??? 我主要谈如下两种方法. (一).传统的form表单方法 <form action="/Home/SaveFile1&q ...

  7. 微信小程序云开发-云存储-上传文件(图片/视频)到云存储 精简代码

    说明 图片/视频这类文件是从客户端会话选择文件. 一.wxml文件添加if切换显示 <!--上传文件到云存储--> <button bindtap="chooseImg&q ...

  8. input文件类型上传,或者作为参数拼接的时候注意的问题!

    1.ajax请求参数如果为文本类型,直接拼接即可.如果为file类型就需要先获取文件信息 2.获取文件信息: HTML代码: <div class="form-group"& ...

  9. java通过ftp和sftp上传war包上传到Linux服务器实现自动重启tomcat的脚本代码

    ar包自动上传Linux并且自动重启tomcat 用的是jdk1.7出的文件监控 支持ftp和sftp,支持多服务器负载等 配置好config 非maven项目导入直接使用 #\u76D1\u542C ...

随机推荐

  1. python的pickle和shelve模块

    python中用于序列化的模块总结 目录 pickle模块 shelve模块 xml模块 pickle模块 介绍 Pickle的问题和所有其他编程语言特有的序列化问题一样,就是它只能用于Python, ...

  2. .NET Core中使用Docker

    一.Docker简介 Docker是基于Linux容器技术(LXC),使用Go语言实现的开源项目,诞生于2013年,遵循Apache2.0协议.Docker自开源后,受到广泛的关注和讨论. Docke ...

  3. 安卓工作室 android studio 的 汉化 美化 定制 Android studio's Chinesization beautification customization

    安卓工作室 android studio 的 汉化 美化 定制 Android studio's Chinesization beautification customization 汉化包 百度云盘 ...

  4. SPOJTLE - Time Limit Exceeded(高维前缀和)

    题意 题目链接 题目的意思是给一个数组C,长度为n,每个数字的范围是2^m,然后要求构造一个数组a,满足 1.a[i] % C[i] !=0 ; 2.a[i] < 2^m ; 3.a[i] &a ...

  5. swoole深入学习 3. upd Server和udp Client

    前面主要讲了tcp得server和client的业务处理,tcp有三次握手,有连接的概览,而UDP服务器与TCP服务器不同,UDP没有连接的概念.启动Server后,客户端无需Connect,直接可以 ...

  6. Redis集群方案总结

    Redis集群方案总结 Redis集群方案总结Codis其余方案Redis cluster 目前,Redis中目前集群有以下几种方案: 主从复制 哨兵模式 redis cluster 代理 codis ...

  7. 喵哈哈村的魔法考试 Round #13 (Div.2) 题解

    喵哈哈村的木星传说(一) 旋转90°,找找规律就知道(x,y)->(n-1-y,x) 然后输出就好了. #include<bits/stdc++.h> using namespace ...

  8. og4j日志文件乱码问题的解决方法

    现象:在默认语言非中文(或者说默认语言不支持中文的)的Windows.Linux.Unix上,用log4j打印日志,出现乱码,常见的就是一堆问号. 解决方法: 如果是log4j.properties为 ...

  9. 虚拟机搭建和安装Hadoop及启动

    马士兵hadoop第一课:虚拟机搭建和安装hadoop及启动 马士兵hadoop第二课:hdfs集群集中管理和hadoop文件操作 马士兵hadoop第三课:java开发hdfs 马士兵hadoop第 ...

  10. C#获取类名为Internet_Explorer_Server控件的内容

    为了让大家都能够使用demo,我以IE为测试对象,另外为了突出重点,所以如何获取窗口句柄我就不做演示了(不清楚的童鞋,可以去Google下哈),句柄值我使用spy++获得 大家可以下载demo(附:s ...