把上传过来的多张图片拼接转为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 ...
随机推荐
- [OpenCV-Python] OpenCV 中的 Gui特性 部分 II
部分 IIOpenCV 中的 Gui 特性 OpenCV-Python 中文教程(搬运)目录 4 图片 目标 • 在这里你将学会怎样读入一幅图像,怎样显示一幅图像,以及如何保存一幅图像 • 你将要学习 ...
- 029.Docker Compose部署Zabbix实战
一 前期规划 1.1 Zabbix架构图 1.2 其他规划 组件 类型 版本 备注 Zabbix Web zabbix-web-apache-mysql镜像 wordpress:latest 也可采用 ...
- Android 打造自己的ImageLoader
Android 打造自己的ImageLoader 学习和参考 Android开发艺术探索 https://blog.csdn.net/column/details/15318.html 郭霖大神的Gl ...
- Javascript日常编码中的一些常见问题
一.尽量少用全局变量 这是一个疑问最少,同时流传最 广的一条.Javascript使用函数管理作用域,全局变量最大的问题在于同名变量冲突.这种隐患产生比较直接的两个原因就是Javascript语言 ...
- Python图形编程探索系列-06-按钮批量生产函数
设计任务 初步设计一个批量生产按钮的函数,根据需要的按钮数量,自动生成多少按钮. 函数设计 import tkinter as tk # 导入tkinter库 root = tk.Tk() # 建立程 ...
- Java并发程序设计(九)设计模式与并发之不变模式
设计模式与并发之不变模式 使用不变模式的目的:除去多线程中的同步操作,提高并行程序的性能. 一个类在的内部状态创建后,在整个生命周期内都不会发生改变,该类就是不变类. /** * @author: T ...
- php integer
一.整数的表示方法: 整型值可以使用十进制,十六进制,八进制或二进制表示,前面可以加上可选的符号(- 或者 +) 要使用二进制表达,数字前必须加上 0b 要使用八进制表达,数字前必须加上 0. 要使用 ...
- 话说extern和static
以前对extern.static的一些东西一直模棱两可.今天好好来梳理了一番.. static关键字 被static修饰的变量或函数称之为静态成员.函数. 存储位置:static修饰的变量存放在静态区 ...
- JNI编程实现(Windows)
上一篇介绍了Linux平台的JNI编程方法,Windows平台的JNI本地调用基本类似,区别就是制作的动态库不同,Linux平台是*.so,Windows平台是*.dll.其中,Windows平台的函 ...
- sitemap xml文件生成
sitemap xml生成方法 <?php /** * SitemapService.php. * * 生成sitemap */ class Sitemap { public $newLine ...