把上傳過來的多張圖片拼接轉為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 = 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;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM