把上传过来的多张图片拼接转为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】 剑指offer(15) 数值的整数次方
本文参考自<剑指offer>一书,代码采用Java语言. 更多:<剑指Offer>Java实现合集 题目 实现函数double Power(double base, int ...
- 014 在Spark中完成PV与UV的计算,重在源代码
1.代码 object LogPVAndUV{ def main(args:Array[String]):Unit={ val conf=new SparkConf() .setMaster(&quo ...
- POJ - 1266 -
题目大意:给出一条圆弧上的两个端点A,B,和圆弧上两端点之间的一个点C,现在要用一块各个定点的坐标均为整数的矩形去覆盖这个圆弧,要求最小的矩形面积. 思路:叉积在本体发挥很强大的作用.首先求出三个点所 ...
- HDU 2222 Keywords Search (AC自动机)(模板题)
<题目链接> 题目大意: 给你一些单词,和一个字符串,问你这个字符串中含有多少个上面的单词. 解题分析: 这是多模匹配问题,如果用KMP的话,对每一个单词,都跑一遍KMP,那么当单词数量非 ...
- Spring框架学习10——JDBC Template 实现数据库操作
为了简化持久化操作,Spring在JDBC API之上提供了JDBC Template组件. 1.添加依赖 添加Spring核心依赖,MySQL驱动 <!--Spring核心基础依赖--> ...
- Git学习笔记:基础篇
git可以说是所有开发者出开发语言之外的最基本的基本功了,熟悉git可以方便的进行代码版本控制,以及与其他开发者进行合作开发.本文内容是我以往学习git时做的笔记,主要是关于git最基本的操作,但 只 ...
- C#如何打开一个窗体,同时关闭该窗体
- R1题解
估分 大佬们都去写题解了,我不写可能会被老师训诶.... 预计分数:100 + 100 + 5 + 100 + 25 + 100 = 430 实际 :80 + 100 + 0 + 100 + 25 + ...
- 专业方向系列-00-Python与有限元初探
案例1 给出4个弹簧的劲度系数,离散后,求其总的刚度矩阵. 代码: import numpy as np k1, k2, k3, k4 = 500, 250, 2000, 1000 ki = np.a ...
- mac下搭建node+koa2项目
1.安装koa sudo npm install koa-generator -g (必须加上 sudo ,否则会报没有权限的错误) 提示输入密码: koa2 node001 npm i 启动:no ...