把上传过来的多张图片拼接转为PDF的实现代码
以下是把上传过来的多张图片拼接转为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的实现代码的更多相关文章
- Android仿微信图片上传,可以选择多张图片,缩放预览,拍照上传等
仿照微信,朋友圈分享图片功能 .可以进行图片的多张选择,拍照添加图片,以及进行图片的预览,预览时可以进行缩放,并且可以删除选中状态的图片 .很不错的源码,大家有需要可以下载看看 . 微信 微信 微信 ...
- angular+ckeditor最后上传的最后一张图片不会被添加(bug)
做法一: angularJs+ckeditor 一.页面 <textarea ckeditor required name="topicContent" ng-model=& ...
- Android图片上传,可以选择多张图片,缩放预览,拍照上传等
仿照微信,朋友圈分享图片功能 .可以进行图片的多张选择,拍照添加图片,以及进行图片的预览,预览时可以进行缩放,并且可以删除选中状态的图片 .很不错的源码,大家有需要可以下载看看 . 微信 微信 微信 ...
- 微信小程序上传一或多张图片
一.要点 1.选取图片 wx.chooseImage({ sizeType: [], // original 原图,compressed 压缩图,默认二者都有 sourceType: [], // a ...
- PHP结合Ueditor并修改图片上传路径 微信小程序 拼接域名显示图片
前言 在使用UEditor编辑器时,一般我们都是需要修改默认的图片上传路径的,下面是我整理好的修改位置和方法供大家参考. 操作 Ueditor PHP版本本身自带了一套上传程序,我们可以在此基础中,找 ...
- H5利用formData来上传文件(包括图片,doc,pdf等各种格式)方法小结!
H5页面中我们常需要进行文件上传,那么怎么来实现这个功能呢??? 我主要谈如下两种方法. (一).传统的form表单方法 <form action="/Home/SaveFile1&q ...
- 微信小程序云开发-云存储-上传文件(图片/视频)到云存储 精简代码
说明 图片/视频这类文件是从客户端会话选择文件. 一.wxml文件添加if切换显示 <!--上传文件到云存储--> <button bindtap="chooseImg&q ...
- input文件类型上传,或者作为参数拼接的时候注意的问题!
1.ajax请求参数如果为文本类型,直接拼接即可.如果为file类型就需要先获取文件信息 2.获取文件信息: HTML代码: <div class="form-group"& ...
- java通过ftp和sftp上传war包上传到Linux服务器实现自动重启tomcat的脚本代码
ar包自动上传Linux并且自动重启tomcat 用的是jdk1.7出的文件监控 支持ftp和sftp,支持多服务器负载等 配置好config 非maven项目导入直接使用 #\u76D1\u542C ...
随机推荐
- java基础面试题-2
第一,谈谈final, finally, finalize的区别. final---修饰符(关键字)如果一个类被声明为final,意味着它不能再派生出新的子类,不能作为父类被继承.因此一个类不能既被 ...
- mongoDB的配置以及运行
干嘛的:数据库,nosql(非关系型) 场景:解决大规模数据集合多重数据种类 一.mongoDb安装: 下载地址: https://www.mongodb.com/download-center ...
- 005.HAProxy+Keepalived高可用负载均衡
一 基础准备 1.1 部署环境及说明 系统OS:CentOS 6.8 64位 HAProxy软件:HA-Proxy version 1.5.18 Keepalived软件:keepalived-1.3 ...
- c# 深入探索之CLR
概念: CLR : 公共语言运行时(Common Language Runtime) 是一个可由多种编程语言使用的"运行时",它负责资源管理(内存分配和垃圾收集等),并保证应用和底 ...
- 玩转SpringCloud(F版本) 四.路由网关(zuul)
本篇文章基于: 01)玩转SpringCloud 一.服务的注册与发现(Eureka) 02) 玩转SpringCloud 二.服务消费者(1)ribbon+restTemplate 03) 玩转Sp ...
- 虚拟机克隆后导致两台机器的IP都不显示的解决方法
centos7中输入ifconfig出现ens33,没有eth0,也没有ip,不能上网,输入ifconfig后如下图 之前在网上也找了很多的方法,比如删除文件70-persistent-ipoib.r ...
- C# 遍历控件 示例
foreach(Control c in tabControl1.TabPages)//这个循环的意思是说,遍历tabControl1中所有的TabPages,TabPages是包含在tabContr ...
- Web大前端面试题-Day10
1. px和em的区别? px和em都是长度单位; 区别是: px的值是固定的,指定是多少就是多少, 计算比较容易. em得值不是固定的,并且em会继承父级元素的字体大小. 浏览器的默认字体高都是16 ...
- 仙剑奇侠传 游戏 开发 教程 Xianjian qixia development Game development tutorial
仙剑奇侠传 开发 游戏 开发 教程 Xianjian qixia development Game development tutorial 作者:韩梦飞沙 Author:han_meng_fei_ ...
- Codeforces Round #514 (Div. 2)
目录 Codeforces 1059 A.Cashier B.Forgery C.Sequence Transformation D.Nature Reserve(二分) E.Split the Tr ...