首页 > 编程语言 >C# http地址下载(后缀.pdf/.jpg/.docx)文件

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

时间:2023-04-03 17:47:04浏览次数:43  
标签:docx http string C# text iTextSharp new pdf document

一、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;
        }

  

标签:docx,http,string,C#,text,iTextSharp,new,pdf,document
From: https://www.cnblogs.com/lydj/p/17283779.html

相关文章

  • Google BigQuery - .NET/C# API Reference Documentation
    .NET Documentation ReferenceWasthishelpful? SendfeedbackGoogle.Cloud.BigQuery.V2bookmark_borderGoogle.Cloud.BigQuery.V2 isa.NETclientlibraryforthe GoogleBigQueryAPI.Itwrapsthe Google.Apis.Bigquery.v2 generatedlibrary,prov......
  • C#如何更新配置文件中的连接字符串
    以MySql为例,其它数据库使用方法一样说明:正常情况下,如果数据库在本机,尽量使用Windows身份验证,如果不在本机,连接字符串里的密码也是需要加密存储,本文只做演示,所以直接使用明文密码。如下在App.config中添加了两条如下连接字符串   第一条是使用ADO.Net使用的连接字符串,第......
  • Low-Code,一定“low”吗?
    作者:京东保险吴凯前言低代码是一组数字技术工具平台,基于图形化拖拽、参数化配置等更为高效的方式,实现快速构建、数据编排、连接生态、中台服务。通过少量代码或不用代码实现数字化转型中的场景应用创新。本文将重点介绍低代码相关知识,包括低代码的定义与意义、相关概念、行业发......
  • EasyCVR插件工具:如何删除EasyShark的抓包数据?
    在前期的文章中,我们分享了关于EasyCVR平台新增的插件工具,感兴趣的用户可以查看这篇文章:《EasyCVR视频融合平台开放插件功能:支持EasyNTS与EasyShark》。其中,EasyShark是用于抓包的工具,支持在客户端直接抓包查看服务器的SIP消息。但是,有用户反馈,由于经常抓包产生了大量的数据,不知道如......
  • Hystrix(一):为什么@EnableCircuitBreaker和@HystrixCommand能驱动Hystrix
    一、@EnableCircuitBreakerEnableCircuitBreaker源码如下:从源码看出实例化了@EnableCircuitBreaker注解实例化了EnableCircuitBreakerImportSelector这个类。再来看EnableCircuitBreakerImportSelector源码:EnableCircuitBreakerImportSelector继承了SpringFactoryImportSelector,Spr......
  • 多精度 simulator 中的 RL:一篇 14 年 ICRA 的古早论文
    目录全文快读0abstract1intro2relatedwork3背景&假设3.1RL&KWIK(knowwhatitknows)的背景3.2问题定义4Multi-FidelityBanditOptimization4.1MF寻找最优arm的算法(MF-bandit)4.2一个例子4.3理论证明5Multi-FidelityRL5.1MFRLalgorithm5.2一个例子5.3理论......
  • Java记录唯一性check
    /***记录唯一性check**@paramid主键*@paramentity实体记录,必须实现equals()方法才能验证更新的场合*@paramfields唯一键字段名称*/if(entity==null||fields.length==0){return;}try{@SuppressWarnings("unchecked")......
  • shellcode获取MessageBoxA的地址
    _asm{pushebpmoveax,fs:[30h];获得PEB地址moveax,[eax+0ch];获得LDR地址moveax,[eax+14h];获得PEB_LDR_DATA中InMemoryOrderModuleList的Flinkmovecx,eax;因为eax中的Flink也就是等于LDR_DATA_TABLE_ENTRY......
  • background-color 只填充容器的一半
     关键字的取值:toright  (表示从左往右渐变)toleft    (表示从右往左渐变)totop    (表示从下往上渐变)tobottom (表示从上往下渐变)角度的取值: 0deg  (从下到上totop)  180deg(从上到下tobottom)90deg  (从左到右toright)-90deg......
  • Chrome103版本获取不到sessionStorage
    问题现象:上传附件功能报错,经排查发现,是因为上送字段中userId获取失败,被服务端拒绝请求。userId=window.sessionStorage.getItem('userId')问题暴露阶段:生产环境Chrome103问题原因:上传功能是在新弹开tab页中实现的,Chrome89后,新弹开的tab页默认不再共享sessionStorage。而测试环......