亲宝软件园·资讯

展开

C#导出pdf的实现方法(浏览器不预览直接下载)

人气:0

前言

这篇文章主要给大家介绍了关于C#导出pdf的实现方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧

方法如下:

一.接口部分的代码

[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;
      }
    }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论