把上傳過來的多張圖片拼接轉為PDF的實現程式碼
阿新 • • 發佈:2018-12-07
以下是把上傳過來的多張圖片拼接轉為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 = 0; for (int i = 0; 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 = 1; //這裡都是圖片最原始的寬度與高度 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 * 100); //讓圖片的中心點與頁面的中心店進行重合 //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 = 0; foreach (var file in fileList) { if (extensionList.Contains(Path.GetExtension(file).ToLower())) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(file); float percentage = 1; //這裡都是圖片最原始的寬度與高度 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 * 100); //讓圖片的中心點與頁面的中心店進行重合 //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 > 0) { //上傳檔案是圖片型別 if (fileType == 1) { bytes = FileUtility.generatePDF2(hfc); } //fileType == 2 上傳檔案是pdf檔案型別 else if (fileType == 2 && hfc[0] != null) { bytes = FileUtility.StreamToBytes(hfc[0].InputStream); } } return bytes; } public static byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 設定當前流的位置為流的開始 stream.Seek(0, 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") ? 1 : 0 }, 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') >= 0) { bootbox.alert(e.message); //location.href = '/Account/Login'; window.location.reload(); } else { bootbox.alert(e.message); $("#loading").hide(); $(this).removeAttr("disalbed"); } } } ) return false; }