首页 > 编程语言 >C# byte[]数据流/base64数据流转pdf文件

C# byte[]数据流/base64数据流转pdf文件

时间:2022-12-26 16:45:20浏览次数:39  
标签:string filePath C# base64 bytes Length pdf byte

pdf转byte[]再转pdf文件进行保存
       /// <summary>
        /// pdf转byte[]再转pdf文件进行保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            string cesi1 = AppDomain.CurrentDomain.BaseDirectory + "FilePath\\" + 11 + ".pdf";//测试pdf保存文件

            byte[] bytes = File.ReadAllBytes("C:\\Users\\Administrator\\Desktop\\测试.pdf");//测试pdf文件

            string strResult = byteToHexStr(bytes);//将pdf byte[]数组转16进制字符串
            this.richTextBox1.Text = strResult;
   
            byte[] byteArray = StrToHexByte(strResult);//将16进制的字符串 转为byte[]

            System.IO.File.WriteAllBytes(@cesi1, byteArray);//根据byte[]数组输出保存pdf文件
        }

        /// <summary> 
        /// 字节数组转16进制字符串 
        /// </summary> 
        /// <param name="bytes"></param> 
        /// <returns></returns> 
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
        /// <summary>
        /// 将16进制的字符串转为byte[]
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] StrToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
pdf base64数据流转pdf文件
方法一: /// <summary> ///Base64数据流转pdf /// </summary> /// <param name="strIn"></param> public void Base64Pdf(string strIn) { try { var filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString(); filePath = filePath + "PdfRecord"; //判断是否有对应文件夹,没有则创建 if (Directory.Exists(filePath) == false) { Directory.CreateDirectory(filePath); } filePathSet = filePath; var filePathInfo = filePath + "\\" + "cesi" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf"; base64StringToPdf(strIn, filePathInfo); } catch (Exception ex) { LogHelper.WriteLog(GetType(), "Base64Pdf异常错误为:" + ex.Message); } } /// <summary> /// base64 转PDF /// </summary> /// <param name="base64Content"></param> /// <param name="filePath"></param> public void base64StringToPdf(String base64Content, String filePath) { try { LogHelper.WriteLog(GetType(), "进入base64StringToPdf方法,入参为:" + base64Content + "路径为:" + filePath); base64Content = base64Content.Replace("data:application/pdf;filename=generated.pdf;base64,", string.Empty); string base64ContentData = base64Content.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+"); if (base64ContentData.Length % 4 > 0) { base64ContentData = base64ContentData.PadRight(base64ContentData.Length + 4 - base64ContentData.Length % 4, '='); } byte[] bytes = Convert.FromBase64String(base64ContentData); string location = filePath; System.IO.FileStream stream = new FileStream(location, FileMode.CreateNew); System.IO.BinaryWriter writer = new BinaryWriter(stream); writer.Write(bytes, 0, bytes.Length); writer.Close(); } catch (Exception ex) { LogHelper.WriteLog(GetType(), "base64StringToPdf异常错误为:" + ex.Message); } } 方法二: private void button1_Click(object sender, EventArgs e) { string fName = "C:\\Users\\Administrator\\Desktop\\bin\\Debug\\测试.pdf"; byte[] b = File.ReadAllBytes(fName); string str = Convert.ToBase64String(b); //byte[] 转string this.richTextBox1.Text = str;//获取base64数据流 } private void button2_Click(object sender, EventArgs e) { string str = this.richTextBox1.Text;//获取base64数据流 byte[] imageBytes = Convert.FromBase64String(str);//string转byte[] File.WriteAllBytes(@"c:\test.Pdf", imageBytes);//保存pdf文件 }

 

标签:string,filePath,C#,base64,bytes,Length,pdf,byte
From: https://www.cnblogs.com/lydj/p/17006149.html

相关文章

  • EtherCAT
    EtherCAT源码https://github.com/OpenEtherCATsociety/SOEM在github上获取.zip格式源码并解压,目前master分支上默认是最新的1.4.0版本。进入根目录,README.md有编译步骤......
  • CompletableFuture 专题
     @Bean("taskExecutor")publicExecutorgetAsyncExecutor(){ThreadPoolTaskExecutorexecutor=newThreadPoolTaskExecutor();executor.setCoreP......
  • 【C++入门】(四)数组
    一. 一维数组1.1 数组的定义//数组的定义方式和变量类似。#include<iostream>#include<algorithm>usingnamespacestd;intmain(){inta[10],b[10];......
  • https Java SSL Exception protocol_version
      在java代码中,使用HttpClient爬取https页面时,遇到了这个bug:javax.net.ssl.SSLException:Receivedfatalalert:protocol_version     先奉上初始的代码:1/**2......
  • javascript使用正则表达式替换或者捕获子字符串
    letstring='mutiFile[{"name":"新建文件夹(2).zip","ext":".zip","size":1675876,"path":"/static/upload/2022December/ba145698fcc99fd414f0f4ec6ea418e5.zip"}]';......
  • 1、C++环境与编译
    C++环境与编译章节概览我们将在本章讨论以下内容:a.什么是一个程序(抽象与实现)b.什么是程序的程序的开发环境c.什么是程序的编译d.什么是IDE、compiler、assembler、li......
  • C++项目中编译部分C的代码
    在C++项目中如果真能编译部分C的代码,那么一定会用到一下语句#ifdef__cplusplusextern"C"{#endif/*...*/#ifdef__cplusplus}#endif下面......
  • v-charts配置y轴刻度自动最小值
    yAxis.min 坐标轴刻度最小值。可以设置成特殊值'dataMin',此时取数据在该轴上的最小值作为最小刻度。不设置时会自动计算最小值保证坐标轴刻度的均匀分布。在类目......
  • apscheduler mysql 持久化任务
    apschedulermysql持久化任务1、下载第三方包这里使用pymysql连接mysqlpipinstallapschedulerpipinstallpymysqlpipinstallsqlalchemy2、直接参考代码imp......
  • MapReduce实战之过滤日志及自定义日志输出路径案例(自定义OutputFormat)
    1)需求      过滤输入的log日志中是否包含atguigu      (1)包含atguigu的网站输出到e:/atguigu.log      (2)不包含atguigu的网站输出到e:/other.log2)输入......