base64 to pdf
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace HS.Common.Helper 9 { 10 public class PdfHelper 11 { 12 //定义一个用于保存静态变量的实例 13 private static PdfHelper instance = null; 14 //定义一个保证线程同步的标识 15 private static readonly object locker = new object(); 16 //构造函数为私有,使外界不能创建该类的实例 17 private PdfHelper() { } 18 public static PdfHelper Instance 19 { 20 get 21 { 22 if (instance == null) 23 { 24 lock (locker) 25 { 26 if (instance == null) instance = new PdfHelper(); 27 } 28 } 29 return instance; 30 } 31 } 32 33 public void ConvertBase64ToPdf(string base64String, string outputPath) 34 { 35 base64String = base64String.Replace("data:application/pdf;filename=generated.pdf;base64,", string.Empty); 36 base64String = base64String.Replace("data:application/pdf;base64,", string.Empty); 37 // 将base64字符串转换为字节数组 38 byte[] pdfBytes = Convert.FromBase64String(base64String); 39 //if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath); 40 //File.WriteAllBytes(@"c:\test.Pdf", imageBytes);//保存pdf文件 41 // 将字节数组写入到PDF文件 42 File.WriteAllBytes(outputPath, pdfBytes); 43 } 44 45 /// <summary> 46 /// base64 转PDF 47 /// </summary> 48 /// <param name="base64Content"></param> 49 /// <param name="filePath"></param> 50 public string Base64StringToPdf(string base64Content, string filePath) 51 { 52 try 53 { 54 base64Content = base64Content.Replace("data:application/pdf;filename=generated.pdf;base64,", string.Empty); 55 base64Content = base64Content.Replace("data:application/pdf;base64,", string.Empty); 56 57 string base64ContentData = base64Content.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+"); 58 if (base64ContentData.Length % 4 > 0) 59 { 60 base64ContentData = base64ContentData.PadRight(base64ContentData.Length + 4 - base64ContentData.Length % 4, '='); 61 } 62 byte[] bytes = Convert.FromBase64String(base64ContentData); 63 64 string location = filePath; 65 System.IO.FileStream stream = new FileStream(location, FileMode.CreateNew); 66 System.IO.BinaryWriter writer = new BinaryWriter(stream); 67 writer.Write(bytes, 0, bytes.Length); 68 writer.Close(); 69 70 } 71 catch (Exception ex) 72 { 73 } 74 return filePath; 75 } 76 77 78 //public string GetDownPdftoBase64(string url, string json) 79 //{ 80 // HttpWebResponse httprec = InsuranceSSXHttpHelp.CreateGetHttpResponse(url, 30, "", null); 81 // string filename = System.DateTime.Now.ToString("yyyyMMddHHmmssfff"); 82 // string path = System.Environment.CurrentDirectory + @"\temp" + @"\" + System.DateTime.Now.ToString("yyyyMMdd") + @"\print\"; 83 // string filepath = InsuranceSSXHttpHelp.HttpDownloadPrint(httprec, path, filename); 84 // return Base64StringByPdf(filepath); 85 //} 86 87 /// <summary> 88 /// base64 to pdf 89 /// </summary> 90 /// <param name="base64"></param> 91 /// <param name="path">文件路径</param> 92 /// <param name="filename">文件名称</param> 93 /// <returns></returns> 94 public string Base64ToPdf(string base64, string path, string filename) 95 { 96 path = path + filename; 97 base64 = base64.Replace("data:application/pdf;filename=generated.pdf;base64,", string.Empty); 98 base64 = base64.Replace("data:application/pdf;base64,", string.Empty); 99 byte[] bytes = Convert.FromBase64String(base64); 100 101 FileStream stream = new FileStream(path, FileMode.CreateNew); 102 BinaryWriter writer = new BinaryWriter(stream); 103 writer.Close(); 104 return path; 105 } 106 107 /// <summary> 108 /// file to base64 109 /// </summary> 110 /// <param name="file"></param> 111 /// <returns></returns> 112 public string Base64StringByPdf(string file) 113 { 114 byte[] bytes = null; 115 FileStream fileStream = new FileStream(file, FileMode.Open); 116 bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); 117 fileStream.Close(); 118 return Convert.ToBase64String(bytes); 119 } 120 121 122 public string UploadBase64ToPdf(string url, string base64) 123 { 124 string path = Environment.CurrentDirectory + @"\GSYBTEMP" + @"\" + System.DateTime.Now.ToString("yyyyMMdd") + @"\"; 125 if (!Directory.Exists(path)) Directory.CreateDirectory(path); 126 127 string filename = "GSYB"+DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf"; 128 //path = Base64ToPdf(base64, path, filename); 129 ConvertBase64ToPdf(base64, path+filename); 130 131 string temp = FileHelper.Instance.UploadFile(url, path+ filename, filename); 132 133 if (Directory.Exists(path)) Directory.Delete(path,true); 134 return temp; 135 } 136 137 } 138 }
上传文件至指定位置
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Net; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace HS.Common.Helper 10 { 11 public class FileHelper 12 { 13 //定义一个用于保存静态变量的实例 14 private static FileHelper instance = null; 15 //定义一个保证线程同步的标识 16 private static readonly object locker = new object(); 17 //构造函数为私有,使外界不能创建该类的实例 18 private FileHelper() { } 19 public static FileHelper Instance 20 { 21 get 22 { 23 if (instance == null) 24 { 25 lock (locker) 26 { 27 if (instance == null) instance = new FileHelper(); 28 } 29 } 30 return instance; 31 } 32 } 33 34 /// <summary> 35 /// 上传文件 36 /// </summary> 37 /// <param name="address">url</param> 38 /// <param name="fileNamePath">本地文件夹路径</param> 39 /// <param name="saveName">文件名称</param> 40 /// <returns></returns> 41 public string UploadFile(string address, string fileNamePath, string saveName) 42 { 43 string returnValue = ""; 44 // 要上传的文件 45 FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); 46 BinaryReader r = new BinaryReader(fs); 47 //时间戳 48 string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); 49 byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); 50 //请求头部信息 51 StringBuilder sb = new StringBuilder(); 52 sb.Append("--"); 53 sb.Append(strBoundary); 54 sb.Append("\r\n"); 55 sb.Append("Content-Disposition: form-data; name=\""); 56 sb.Append("file"); 57 sb.Append("\"; filename=\""); 58 sb.Append(saveName); 59 sb.Append("\""); 60 sb.Append("\r\n"); 61 sb.Append("Content-Type: "); 62 sb.Append("application/octet-stream"); 63 sb.Append("\r\n"); 64 sb.Append("\r\n"); 65 string strPostHeader = sb.ToString(); 66 byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); 67 // 根据uri创建HttpWebRequest对象 68 HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address)); 69 httpReq.Method = "POST"; 70 //对发送的数据不使用缓存 71 httpReq.AllowWriteStreamBuffering = false; 72 //设置获得响应的超时时间(300秒) 73 httpReq.Timeout = 60000; 74 httpReq.ReadWriteTimeout = 60000; 75 httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary; 76 httpReq.Accept = "application/json"; 77 long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length; 78 long fileLength = fs.Length; 79 httpReq.ContentLength = length; 80 try 81 { 82 //每次上传4k 83 int bufferLength = 10240; 84 byte[] buffer = new byte[bufferLength]; 85 //已上传的字节数 86 long offset = 0; 87 //开始上传时间 88 DateTime startTime = DateTime.Now; 89 int size = r.Read(buffer, 0, bufferLength); 90 Stream postStream = httpReq.GetRequestStream(); 91 //发送请求头部消息 92 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); 93 while (size > 0) 94 { 95 postStream.Write(buffer, 0, size); 96 size = r.Read(buffer, 0, bufferLength); 97 } 98 //添加尾部的时间戳 99 postStream.Write(boundaryBytes, 0, boundaryBytes.Length); 100 postStream.Close(); 101 //获取服务器端的响应 102 WebResponse webRespon = httpReq.GetResponse(); 103 Stream s = webRespon.GetResponseStream(); 104 StreamReader sr = new StreamReader(s); 105 //读取服务器端返回的消息 106 String sReturnString = sr.ReadLine(); 107 s.Close(); 108 sr.Close(); 109 return sReturnString; 110 } 111 catch (Exception ex) 112 { 113 returnValue = -1 + "@" + ex.ToString(); 114 } 115 finally 116 { 117 fs.Close(); 118 r.Close(); 119 } 120 return returnValue; 121 } 122 123 /// <summary> 124 /// 删除指定目录及文件 125 /// </summary> 126 /// <param name="pathDir"></param> 127 public void DelFullPath(string pathDir) 128 { 129 try 130 { 131 DirectoryInfo dir = new DirectoryInfo(pathDir); 132 FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录 133 foreach (FileSystemInfo i in fileinfo) 134 { 135 if (i is DirectoryInfo) //判断是否文件夹 136 { 137 DirectoryInfo subdir = new DirectoryInfo(i.FullName); 138 subdir.Delete(true); //删除子目录和文件 139 } 140 else 141 { 142 File.Delete(i.FullName); //删除指定文件 143 } 144 } 145 } 146 catch (Exception e) 147 { 148 throw; 149 } 150 } 151 152 } 153 }
调用方式:
string base64 = PubVariable.Instance.JsonPdfFileBase64;
string uploadUrl = "https://dev.his.yfttech.cn/hs/openplatform/epc_client/callback/upload";
PdfHelper.Instance.UploadBase64ToPdf(uploadUrl, base64 );