C# http地址下载(后缀.pdf/.jpg/.docx)文件

发布时间 2023-04-03 17:42:21作者: fulllove
一、http后缀.pdf文件下载方法
 /// <summary>
        /// http地址文件下载(url路径格式为:http://192.168.1.218:8088/1231_tr/1762062.pdf"})
        /// </summary>
        /// <param name="filePath">http文件下载路径</param>
        /// <param name="startPath">文件保存路径c:C:\Downloads\ces.pdf</param>
        /// <returns></returns>
        public string httppdf(string filePath, string startPath)
        {
            try
            {
                //FileStream fs = new FileStream(startPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                FileStream fs = null;
                // 设置参数
                HttpWebRequest request = WebRequest.Create(filePath) as HttpWebRequest;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求

                Stream responseStream = response.GetResponseStream();
                //创建本地文件写入流
                //Stream stream = new FileStream(tempFile, FileMode.Create);

                byte[] bArr = new byte[4096];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                if (size > 0)
                {
                    fs = new FileStream(startPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    while (size > 0)
                    {
                        //stream.Write(bArr, 0, size);
                        fs.Write(bArr, 0, size);
                        size = responseStream.Read(bArr, 0, (int)bArr.Length);
                    }
                    fs.Close();
                }
                else
                {
                    LogHelper.WriteLog(GetType(), "HttpDownloads:Return Nothing");
                    return "";
                }

                responseStream.Close();
                LogHelper.WriteLog(GetType(), "HttpDownloads:下载成功,文件路径为" + startPath);
                return startPath;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(GetType(), "HttpDownloads:" + ex.Message);
                return "";
            }
        }

  二、http后缀.jpg文件下载方法

 /// <summary>
        /// .jpg文件下载至本地(url路径格式为:http://192.168.1.219:8088/system/yanshi.jpg"})
        /// </summary>
        /// <param name="filePath">下载路径</param>
        /// <param name="startPath">保存路径C:\Downloads\ce.jpg</param>
        /// <returns></returns>
        public string httpjpg(string filePath, string startPath)
        {
            LogHelper.WriteLog(GetType(), "httpjpg入参下载路径为:" + filePath + "保存路径为:" + startPath);
            string result = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filePath);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (Stream stream = response.GetResponseStream())
                {
                    using (FileStream fileStream = File.Create(startPath))
                    {
                        byte[] buffer = new byte[1024];
                        int bytesRead = 0;
                        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            fileStream.Write(buffer, 0, bytesRead);
                        }
                    }
                }

                response.Close();

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(GetType(), "httpjpg异常错误为:" + ex.Message);
                return "";
            }
            return startPath;
        }


         /// <summary>
        /// JPG转PDF
        /// </summary>
        /// <param name="jpgfile">图片路径C:\Downloads\ce.jpg</param>
        /// <param name="pdf">生成的PDF路径C:\Downloads\ce.pdf</param>
        /// <param name="pageSize">A4,A5</param>
        /// <param name="Vertical">True:纵向,False横向</param>
        public static void ConvertJPG2PDF(string jpgfile, string pdf, string pageSize, bool Vertical = true)
        {
            float width = 0, height = 0;
            Document document;

            #region 根据纸张大小,纵横向,设置画布长宽
            if (pageSize.ToUpper() == "A4")
            {
                if (Vertical)//纵向
                {
                    width = iTextSharp.text.PageSize.A4.Width;
                    height = iTextSharp.text.PageSize.A4.Height;
                }
                else//横向
                {
                    width = iTextSharp.text.PageSize.A4.Height;
                    height = iTextSharp.text.PageSize.A4.Width;
                }
            }
            else if (pageSize.ToUpper() == "A5")
            {
                if (Vertical)
                {
                    width = iTextSharp.text.PageSize.A5.Width;
                    height = iTextSharp.text.PageSize.A5.Height;
                }
                else
                {
                    width = iTextSharp.text.PageSize.A5.Height;
                    height = iTextSharp.text.PageSize.A5.Width;
                }
            }

            iTextSharp.text.Rectangle pageSizeNew = new iTextSharp.text.Rectangle(width, height);
            document = new Document(pageSizeNew);
            #endregion 


            using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None))
            {

                PdfWriter.GetInstance(document, stream);

                document.Open();

                using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var image = iTextSharp.text.Image.GetInstance(imageStream);

                    //缩放图像比例
                    image.ScaleToFit(width, height);
                    image.SetAbsolutePosition(0, 0);

                    image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;

                    document.Add(image);
                }
                document.Close();

            }

        }

  三、http后缀.word文件下载方法

         /// <summary>
        /// 下载word文件:http://222.128.103.58:21909/system-demo/public/img/ces.docx(也可用httpjpg方法进行下载)
        /// </summary>
        /// <param name="url">下载文件路径</param>
        /// <param name="filePath">下载文件保存路径:C:\Downloads\ces.docx</param>
        public void DownloadWordDocument(string url, string filePath)
        {
            var client = new WebClient();
            client.DownloadFile(url, filePath);
        }
        /// <summary>
        /// word转pdf
        /// </summary>
        /// <param name="sourcePath">word文件路径C:\Downloads\CES.pdf</param>
        /// <param name="targetPath">保存pdf文件路径C:\Downloads\ces.pdf</param>
        /// <returns></returns>
        public static bool WordToPDFWithOffice(string sourcePath, string targetPath)
        {
            bool result = false;
            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Document document = null;
            try
            {
                application.Visible = false;
                document = application.Documents.Open(sourcePath);
                /*
                 参数参考 https://docs.microsoft.com/zh-cn/office/vba/api/visio.document.exportasfixedformat
                 */
                //  document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportFromTo);
                document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument);
                result = true;
            }
            catch (Exception e)
            {
                //Console.WriteLine(e.Message);
                result = false;
            }
            finally
            {
                document.Close();
            }
            return result;
        }