首页 > 知识百科 > 正文

C 实现网页内容保存为图片并生成压缩包 原创

目录

应用场景

实现代码

扩展功能(生成压缩包)

小结


应用场景

我们在一个简历打印的项目功能里,需要根据一定的查询条件,得到结果并批量返回指定格式的文件。导出的格式可能有多种,比如WORD格式、EXCEL格式、PDF格式等,实现方式是通过设置对应的模板进行输出,实际情况是,简历的内容是灵活设置的,没有固定的格式,模板数量不固定的。

通过动态页面技术,可以实现简历配置后的网页内容输出,但制作对应的各种模板会遇到开发效率和服务消耗的问题。稿件输出,折中而简单的方案就是将动态输出的页面转化为图片格式。

实现代码

创建一个UrlToImage类,创建实例的时候传递指定的URL,并调用SaveToImageFile(string outputFilename)方法,该方法传递要输出的文件名参数即可即可。

调用示例代码如下:

string url = "https://" + Request.Url.Host + "/printResume.aspx";UrlToImage uti = new UrlToImage(url);bool irv = uti.SaveToImageFile(Request. PhysicalApplicationPath + "\\test.jpg");if(bool==false){ Response.Write("保存失败。"); Response.End();}

类及实现代码如下:

 public class UrlToImage { private Bitmap m_Bitmap;私有字符串 m_Url;私有字符串 m_FileName = string.Empty; int initheight = 0; public UrlToImage(string url) { // 没有文件 m_Url = url; } public UrlToImage(string url, string fileName) { // 带文件 m_Url = url; m_FileName = 文件名; } public BitmapGenerate() { // 线程 var m_thread = new Thread(_Generate); m_thread.SetApartmentState(公寓状态.STA); m_thread.Start(); m_thread.Join();返回m_Bitmap; } public bool SaveToImageFile(string filename) { 位图 bt=Generate(); if (bt == null) { 返回 false; } bt.保存(文件名);返回 File.Exists(文件名); } private void _Generate() { var browser = new WebBrowser { ScrollBarsEnabled = false }; browser.ScriptErrorsSuppressed = true;初始高度 = 0;浏览器.Navigate(m_Url); browser.DocumentCompleted += WebBrowser_DocumentCompleted; while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } 浏览器.Dispose(); } private void WebBrowser_DocumentCompleted(对象发送者,WebBrowserDocumentCompletedEventArgs e){ // 捕获 var browser = (WebBrowser)sender; browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom); browser.ScrollBarsEnabled = false; m_Bitmap = new Bitmap(browser.Document.Body.ScrollRectangle.Width, browser.Document.Body.ScrollRectangle.Bottom); browser.BringToFront(); browser.DrawToBitmap(m_Bitmap, browser.Bounds); // 保存为文件? if (m_FileName.Length > 0) { // 保存 m_Bitmap.SaveJPG100(m_FileName); } if (initheight == browser.Document.Body.ScrollRectangle.Bottom) { browser.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted); initheight = browser.Document.Body.ScrollRectangle.Bottom; } }

生成压缩包

对于批量生成的图片文件,我们可以生成压缩包为客户提供下载功能,压缩功能引用的是ICSharpCode.SharpZipLib.dll, 创建ZipCompress类的实例,ZipDirectory (zippath,zipfile,password)方法,需要提供的参数包括,压缩的目录、生成的压缩文件名,压缩包的打开密码。

示例代码如下:

<代码 class="26a8-2fbd-23ea-a6a7 language-cs"> string zippath = Request.PhysicalApplicationPath + "\\des\\" ; if (!Directory.Exists(zippath)) { Directory.CreateDirectory(zippath); } string zipfile = Request.PhysicalApplicationPath + "\\des\\test.zip"; ZipCompress allgzip = new ZipCompress(); System.IO.DirectoryInfo alldi = new System.IO.DirectoryInfo(zippath); 字符串密码 = "123456"; allgzip.ZipDirectory(zippath, zipfile ,password); //以下是生成完成压缩包后,清除目录及文件 string[] allfs = Directory.GetFiles(zippath); for (int i = 0; i < allfs.Length; i++) {文件.Delete(allfs[i]);目录.删除(zippath); 

类及实现代码如下:

 public class ZipCompress { public byte[] Compress(byte[] inputBytes) { using (MemoryStream outStream = new MemoryStream()) { using (GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress, true)) { zipStream.Write(inputBytes, 0, inputBytes.Length); } zipStream.Close(); // 很重要,必须关闭,否则无法正确解压 return outStream.ToArray(); } } } public byte[] Decompress(byte[] inputBytes) { using (MemoryStream inputStream = new MemoryStream(inputBytes)) { using (MemoryStream outStream = new MemoryStream()) { using (GZipStream zipStream = new GZipStream(inputStream, CompressionMode.十二月ompress)) { zipStream.CopyTo(outStream); zipStream.Close();返回 outStream.ToArray(); } } } } 公共字符串压缩(字符串输入){ byte[] inputBytes = Encoding.Default.GetBytes(输入); byte[] 结果 = 压缩(inputBytes);返回 Convert.ToBase64String(结果); } 公共字符串解压缩(字符串输入) { byte[] inputBytes = Convert.FromBase64String(输入); byte[] depressBytes = 解压缩(inputBytes);返回 Encoding.Default.GetString(depressBytes); } public void Compress(DirectoryInfo dir) { foreach (FileInfo fileToCompress in dir.GetFiles()) { compress(fileTocompress); } } } public void Decompress(DirectoryInfo dir) { foreach (FileInfo fileToCompress in dir.GetFiles()) { 解压缩(fileToCompress); } } public void Compress(FileInfo fileTocompress) { using (FileStream originalFileStream = fileTocompress.OpenRead()) { if ((File.GetAttributes(fileTocompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileTocompress.Extension != " .gz") { using (FileStreamcompressedFileStream = File.Create(fileTocompress.FullName + ".gz")) { using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.compress)) {originalFileStream.CopyTo(compressionStream); } } } } } } public void Decompress(FileInfo fileToDecompress,string desfilename="") { using (FileStream originalFileStream = fileToDecompress.OpenRead()) { string currentFileName = fileToDecompress.FullName; } string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length); if (desfilename!= "") { newFileName = desfilename; } using (FileStream decompressedFileStream = File.Create(newFileName)) { using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress)) { decompressionStream.CopyTo(decompressedFileStream); } } } } } public void ZipDirectory(字符串folderToZip,字符串zipedFileName,字符串密码){ ZipDirectory(folderToZip,zipedFileName,(password==""?string.Empty:密码), true, string.Empty, string.Empty, true); } public void ZipDirectory(字符串folderToZip,字符串zipedFileName,字符串密码,bool isRecurse,字符串fileRegexFilter,字符串directoryRegexFilter,bool isCreateEmptyDirectories){ FastZip fastZip = new FastZip(); fastZip.CreateEmptyDirectories = isCreateEmptyDirectories; fastZip.Password = 密码; fastZip.CreateZip(zipedFileName,folderToZip,isRecurse,fileRegexFilter,directoryRegexFilter); } public void UnZipDirectory(string zipedFileName, string targetDirectory, string password,string fileFilter=null) { FastZip fastZip = new FastZip(); fastZip.Password = 密码; fastZip.ExtractZip(zipedFileName, targetDirectory,fileFilter); } public void UnZip(string zipFilePath, string unZipDir) { if(zipFilePath == string.Empty) { throw new Exception("压缩文件不能为空!"); } if (!File.Exists(zipFilePath)) { throw new FileNotFoundException("压缩文件不存在!"); } //解压文件夹为空时默认与压缩文件同名的文件夹下,跟压缩文件同名的文件夹 if (unZipDir == string.Empty) unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension (zip文件路径)); if (!unZipDir.EndsWith("/")) unZipDir += "/"; if (!Directory.Exists(unZipDir)) Directory.CreateDirectory(unZipDir);使用 (var s = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string DirectoryName = Path.GetDirectoryName(theEntry.Name);字符串文件名 = Path.GetFileName(theEntry.Name); if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(unZipDir + directoryName); } if (directoryName != null && !directoryName.EndsWith("/")) { } if (fileName != String.Empty) { using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name)) { int size; }字节[]数据=新字节[2048]; while (true) { size = s.Read(data, 0, data.Length);如果(大小> 0){streamWriter.Write(数据,0,大小);} 否则{ 中断; } } } } } } } }

小结 

用于生成的图片文件,我们还可以结合其他的API应用,来判断图片是否有被PS的情况,来提升和扩展应用程序的功能。另外,对于被访问的动态页面,建议使用控制访问,只有正常登录或提供访问令牌的用户才可以生成结果图片,以保证数据的安全性。

以上代码参考,欢迎大家指正,再次感谢您的阅读!

 

C 实现网页内容保存为图片并生成压缩包 原创由知识百科栏目发布,感谢您对的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“C 实现网页内容保存为图片并生成压缩包 原创