欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 导出pdf(浏览器不预览直接下载)

程序员文章站 2022-08-28 13:35:02
一.接口部分的代码 [HttpGet] public HttpResponseMessage ExportPdf(string id) { string pdfName = ""; //id 查询条件,根据实际情况修改即可 //pdfName 例如download.pdf byte[] pdfDat ......

一.接口部分的代码

        [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模式的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;
            }
        }