SoFunction
Updated on 2025-03-06

Implementation method of exporting pdf in C# (draw directly without previewing)

Preface

This article mainly introduces the implementation method of C# exporting pdf, and shares it for your reference and learning. I won’t say much below, let’s take a look at the detailed introduction together.

The method is as follows:

1. Code of the interface part

[HttpGet]
    public HttpResponseMessage ExportPdf(string id)
    {
      string pdfName = "";
 //id query conditions, modify them according to actual situation //pdfName For example      byte[] pdfData= _policyGapManagerService.ExportPdf(id, out pdfName);//Get pdf bytes      var result = new HttpResponseMessage()
      {
        Content = new ByteArrayContent(pdfData)
      };
       =
        new ContentDispositionHeaderValue("attachment")
        {
          FileName = pdfName
        };
       =new MediaTypeHeaderValue("application/pdf");
      return result;
    }

2. Return pdfbyte array

1. Download the pdf file in http mode (for example, if you store the PDF in the project directory, you can directly open the pdf file under the project through http)

#region Call local file to return pdfbyte array
    /// <summary>
    /// Call the local file to return the pdfbyte array    /// </summary>
    /// <param name="srcPdfFile">‘D:\'</param>
    /// <returns></returns>

    public static byte[] GetSignaturePDFByte(string srcPdfFile)
    {
      using (FileStream fsRead = new FileStream(srcPdfFile, , , ))
      {
        int fsLen = (int);
        byte[] hebyte = new byte[fsLen];
        (hebyte, 0, );
        return hebyte;
      }
    }

    #endregion Call local file to return pdfbyte array
    #region Download pdf from the website and convert it into byte stream

    /// <summary>
    /// Download the pdf from the website and convert it into a byte stream    /// </summary>
    /// <param name="srcPdfFile">File address: 'https://******/group2/M00/00/04/'</param>
    /// &lt;returns&gt;&lt;/returns&gt;
    public static Byte[] GetByteByRemoteURL(string srcPdfFile)
    {
      byte[] arraryByte;
      HttpWebRequest req = (HttpWebRequest)(srcPdfFile);
       = "GET";
      using (WebResponse wr = ())
      {
        StreamReader responseStream = new StreamReader((), Encoding.UTF8);
        int length = (int);
        byte[] bs = new byte[length];

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

        //Read to memory        MemoryStream stmMemory = new MemoryStream();
        byte[] buffer1 = new byte[length];
        int i;
        //Put bytes one by one into Byte        while ((i = (buffer1, 0, )) &gt; 0)
        {
          (buffer1, 0, i);
        }
        arraryByte = ();
        ();
      }
      return arraryByte;
    }

    #endregion Download pdf from the website and convert it into byte stream
    #region Download the file from the website and save it to another path
    /// &lt;summary&gt;
    /// Download the file from the website and save it to another path    /// &lt;/summary&gt;
    /// <param name="pdfFile">File address</param>    /// <param name="saveLoadFile">Save file path: D:\</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public string SaveRemoteFile( string saveLoadFile , string pdfFile)
    {
      //bool flag = false;
      var f = saveLoadFile + ().ToString("D") + ".pdf";
      Uri downUri = new Uri(pdfFile);
      //Create a WEB request and return the HttpWebRequest object      HttpWebRequest hwr = (HttpWebRequest)(downUri);
      //The stream object is automatically closed after use      using (Stream stream = ().GetResponseStream())
      {
        //File stream, stream information is read into the file stream, close after reading        using (FileStream fs = (f))
        {
          //Create a byte group and set its size to what bytes          byte[] bytes = new byte[102400];
          int n = 1;
          while (n &gt; 0)
          {
            //How many bytes are read from the stream at a time and assign the value to N. After reading, N is 0 and exits the loop            n = (bytes, 0, 10240);
            (bytes, 0, n); //Write the stream information of the specified bytes into the file stream          }
        }
      }

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

    #endregion Download files from the website,Save to another path

Pattern pdf file

/// &lt;summary&gt;
    /// Download the FTP file.    /// &lt;/summary&gt;
    /// <param name="offsetPath">Relative Path</param>    /// <param name="fileName">File name</param>    /// <returns>Download results, local file path</returns>    public string DownLoad(string offsetPath,string fileName)
    {
      try
      {
        FtpWebRequest ftpWeb = (FtpWebRequest)(_ftpRootPath + offsetPath + fileName);
         = ;
         = true;
        var resp = ();
        using (FileStream fs = new FileStream(_outPath + fileName, ))
        {
          using (var s = ())
          {
            if (s == null) { return "The file does not exist!"; }

            int readCout = 0;
            byte[] bytes = new byte[1024];
            readCout = (bytes, 0, 1024);
            while (readCout &gt; 0)
            {
              (bytes, 0, readCout);
              readCout = (bytes, 0, 1024);
            }
          }
        }
        ();
        return _outPath + fileName;
      }
      catch (Exception e)
      {
        return ;
      }
      
    }

    /// &lt;summary&gt;
    /// Determine whether the file exists    /// &lt;/summary&gt;
    /// &lt;param name="offsetPath"&gt;&lt;/param&gt;
    /// &lt;param name="fileName"&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public bool FileExists(string offsetPath, string fileName)
    {
      try
      {
        FtpWebRequest ftpWeb = (FtpWebRequest)(_ftpRootPath + offsetPath + fileName);
         = ;
         = true;
        var resp = (FtpWebResponse)();
        ();
        return true;
      }
      catch (Exception)
      {
        return false;
      }
    }

    /// &lt;summary&gt;
    /// Get all files in the directory    /// &lt;/summary&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public string[] Files(string offsetPath)
    {
      try
      {
        FtpWebRequest ftpWeb = (FtpWebRequest)(_ftpRootPath + offsetPath);
         = ;
        Stream stream = ().GetResponseStream();
        if (stream == null)
        {
          return null;
        }
        List&lt;string&gt; fileList = new List&lt;string&gt;();
        using (StreamReader sr = new StreamReader(stream))
        {
          StringBuilder sb = new StringBuilder();
          do
          {
            (());
            if ( &gt; 0)
            {
              (());
              ();
            }
            else
            {
              break;
            }
          } while (true);
        }
        return ();
      }
      catch (Exception)
      {
         return null;
      }
    }

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.