C# 匯出pdf(瀏覽器不預覽直接下載)

chinaherolts2008發表於2020-12-13

一.介面部分的c#教程程式碼

        [HttpGet]
        public HttpResponseMessage ExportPdf(string id)
        {
            string pdfName = "";
       //id 查詢條件,根據實際情況修改即可
       //pdfName 例如download.pdf
            byte[] pdfData= _policyGapManagerService.ExportPdf(id, out pdfName);//獲得pdf位元組
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(pdfData)
            };
            result.Content.Headers.ContentDisposition =
                new ContentDispositionHeaderValue("attachment")
                {
                    FileName = pdfName
                };
            result.Content.Headers.ContentType =new MediaTypeHeaderValue("application/pdf");
            return result;
        }

二.返回pdfbyte陣列

1.下載http模式的pdf檔案(以ASP.NET為例,將PDF存在專案的目錄下,可以通過http直接開啟專案下的pdf檔案)

#region 呼叫本地檔案使用返回pdfbyte陣列

        /// <summary>
        /// 呼叫本地檔案使用返回pdfbyte陣列
        /// </summary>
        /// <param name="srcPdfFile">‘D:\in2434341555551.pdf’</param>
        /// <returns></returns>

        public static byte[] GetSignaturePDFByte(string srcPdfFile)
        {
            using (FileStream fsRead = new FileStream(srcPdfFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                int fsLen = (int)fsRead.Length;
                byte[] hebyte = new byte[fsLen];
                fsRead.Read(hebyte, 0, hebyte.Length);
                return hebyte;
            }
        }

        #endregion 呼叫本地檔案使用返回pdfbyte陣列

        #region 從網站上下載pdf,轉化為位元組流


        /// <summary>
        /// 從網站上下載pdf,轉化為位元組流
        /// </summary>
        /// <param name="srcPdfFile">檔案地址:'https://******/group2/M00/00/04/wKj-mlpcoZ2IUbK5AACrpaV6k98AAAB6gAAAAAAAKu9562.pdf'</param>

        /// <returns></returns>
        public static Byte[] GetByteByRemoteURL(string srcPdfFile)
        {
            byte[] arraryByte;
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(srcPdfFile);
            req.Method = "GET";
            using (WebResponse wr = req.GetResponse())
            {
                StreamReader responseStream = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
                int length = (int)wr.ContentLength;
                byte[] bs = new byte[length];

                HttpWebResponse response = wr as HttpWebResponse;
                Stream stream = response.GetResponseStream();

                //讀取到記憶體
                MemoryStream stmMemory = new MemoryStream();
                byte[] buffer1 = new byte[length];
                int i;
                //將位元組逐個放入到Byte 中
                while ((i = stream.Read(buffer1, 0, buffer1.Length)) > 0)
                {
                    stmMemory.Write(buffer1, 0, i);
                }
                arraryByte = stmMemory.ToArray();
                stmMemory.Close();
            }
            return arraryByte;
        }

        #endregion 從網站上下載pdf,轉化為位元組流

        #region 從網站上下載檔案,儲存到其他路徑

        /// <summary>
        /// 從網站上下載檔案,儲存到其他路徑
        /// </summary>
        /// <param name="pdfFile">檔案地址</param>
        /// <param name="saveLoadFile">儲存檔案路徑:D:\12221.pdf</param>
        /// <returns></returns>
        public string SaveRemoteFile( string saveLoadFile , string pdfFile)
        {
            //bool flag = false;
            var f = saveLoadFile + Guid.NewGuid().ToString("D") + ".pdf";
            Uri downUri = new Uri(pdfFile);
            //建立一個WEB請求,返回HttpWebRequest物件
            HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(downUri);
            //流物件使用完後自動關閉
            using (Stream stream = hwr.GetResponse().GetResponseStream())
            {
                //檔案流,流資訊讀到檔案流中,讀完關閉
                using (FileStream fs = File.Create(f))
                {
                    //建立位元組組,並設定它的大小是多少位元組
                    byte[] bytes = new byte[102400];
                    int n = 1;
                    while (n > 0)
                    {
                        //一次從流中讀多少位元組,並把值賦給N,當讀完後,N為0,並退出迴圈
                        n = stream.Read(bytes, 0, 10240);
                        fs.Write(bytes, 0, n); //將指定位元組的流資訊寫入檔案流中
                    }
                }
            }

            //return flag;
            //return _outPath + saveLoadFile;
            return f;
        }

        #endregion 從網站上下載檔案,儲存到其他路徑

2.ftp模式python基礎教程的pdf檔案


/// <summary>
        /// 下載FTP檔案。
        /// </summary>
        /// <param name="offsetPath">相對路徑</param>
        /// <param name="fileName">檔名稱</param>
        /// <returns>下載結果,本地檔案路徑</returns>
        public string DownLoad(string offsetPath,string fileName)
        {
            try
            {
                FtpWebRequest ftpWeb = (FtpWebRequest)WebRequest.Create(_ftpRootPath + offsetPath + fileName);
                ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpWeb.UseBinary = true;
                var resp = ftpWeb.GetResponse();
                using (FileStream fs = new FileStream(_outPath + fileName, FileMode.Create))
                {
                    using (var s = resp.GetResponseStream())
                    {
                        if (s == null) { return "檔案不存在!"; }

                        int readCout = 0;
                        byte[] bytes = new byte[1024];
                        readCout = s.Read(bytes, 0, 1024);
                        while (readCout > 0)
                        {
                            fs.Write(bytes, 0, readCout);
                            readCout = s.Read(bytes, 0, 1024);
                        }
                    }
                }
                resp.Close();
                return _outPath + fileName;
            }
            catch (Exception e)
            {
                return e.Message;
            }
            
        }

        /// <summary>
        /// 判斷檔案是否存在
        /// </summary>
        /// <param name="offsetPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool FileExists(string offsetPath, string fileName)
        {
            try
            {
                FtpWebRequest ftpWeb = (FtpWebRequest)WebRequest.Create(_ftpRootPath + offsetPath + fileName);
                ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpWeb.UseBinary = true;
                var resp = (FtpWebResponse)ftpWeb.GetResponse();
                resp.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 獲取目錄下所有檔案
        /// </summary>
        /// <returns></returns>
        public string[] Files(string offsetPath)
        {
            try
            {
                FtpWebRequest ftpWeb = (FtpWebRequest)WebRequest.Create(_ftpRootPath + offsetPath);
                ftpWeb.Method = WebRequestMethods.Ftp.ListDirectory;
                Stream stream = ftpWeb.GetResponse().GetResponseStream();
                if (stream == null)
                {
                    return null;
                }
                List<string> fileList = new List<string>();
                using (StreamReader sr = new StreamReader(stream))
                {
                    StringBuilder sb = new StringBuilder();
                    do
                    {
                        sb.Append(sr.ReadLine());
                        if (sb.Length > 0)
                        {
                            fileList.Add(sb.ToString());
                            sb.Clear();
                        }
                        else
                        {
                            break;
                        }
                    } while (true);
                }
                return fileList.ToArray();
            }
            catch (Exception)
            {
                 return null;
            }
        }

相關文章