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

news/2025/2/12 15:30:08/

目录

应用场景

实现代码

扩展功能(生成压缩包)

小结 


应用场景

我们在一个求职简历打印的项目功能里,需要根据一定的查询条件,得到结果并批量导出指定格式的文件。导出的格式可能有多种,比如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("save failed.");Response.End();
}

类及实现代码如下:

    public class UrlToImage{private  Bitmap m_Bitmap;private string m_Url;private string m_FileName = string.Empty;int initheight = 0;public UrlToImage(string url){// Without filem_Url = url;}public UrlToImage(string url, string fileName){// With filem_Url = url;m_FileName = fileName;}public Bitmap Generate(){// Threadvar m_thread = new Thread(_Generate);m_thread.SetApartmentState(ApartmentState.STA);m_thread.Start();m_thread.Join();return m_Bitmap;}public bool SaveToImageFile(string filename){Bitmap bt=Generate();if (bt == null){return false;}bt.Save(filename);return File.Exists(filename);}private void _Generate(){var browser = new WebBrowser { ScrollBarsEnabled = false };browser.ScriptErrorsSuppressed = true;initheight = 0;browser.Navigate(m_Url);browser.DocumentCompleted += WebBrowser_DocumentCompleted;while (browser.ReadyState != WebBrowserReadyState.Complete){Application.DoEvents();}browser.Dispose();}private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e){// Capturevar 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);// Save as file?if (m_FileName.Length > 0){// Savem_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) 方法,需要提供的参数包括,压缩的目录、生成的压缩文件名,压缩包的打开密码。

示例代码如下:

    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);string password = "123456";allgzip.ZipDirectory(zippath, zipfile, password);//以下是生成完压缩包后,清除目录及文件string[] allfs = Directory.GetFiles(zippath);for (int i = 0; i < allfs.Length; i++){File.Delete(allfs[i]);}Directory.Delete(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.Decompress)){zipStream.CopyTo(outStream);zipStream.Close();return outStream.ToArray();}}}}public  string Compress(string input){byte[] inputBytes = Encoding.Default.GetBytes(input);byte[] result = Compress(inputBytes);return Convert.ToBase64String(result);}public  string Decompress(string input){byte[] inputBytes = Convert.FromBase64String(input);byte[] depressBytes = Decompress(inputBytes);return 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()){Decompress(fileToCompress);}}public  void Compress(FileInfo fileToCompress){using (FileStream originalFileStream = fileToCompress.OpenRead()){if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz"){using (FileStream compressedFileStream = 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(string folderToZip, string zipedFileName,string password){ZipDirectory(folderToZip, zipedFileName,(password==""?string.Empty:password), true, string.Empty, string.Empty, true);}public  void ZipDirectory(string folderToZip, string zipedFileName, string password, bool isRecurse, string fileRegexFilter, string directoryRegexFilter, bool isCreateEmptyDirectories){FastZip fastZip = new FastZip();fastZip.CreateEmptyDirectories = isCreateEmptyDirectories;fastZip.Password = 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 = 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(zipFilePath));if (!unZipDir.EndsWith("/"))unZipDir += "/";if (!Directory.Exists(unZipDir))Directory.CreateDirectory(unZipDir);using (var s = new ZipInputStream(File.OpenRead(zipFilePath))){ZipEntry theEntry;while ((theEntry = s.GetNextEntry()) != null){string directoryName = Path.GetDirectoryName(theEntry.Name);string fileName = 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;byte[] data = new byte[2048];while (true){size = s.Read(data, 0, data.Length);if (size > 0){streamWriter.Write(data, 0, size);}else{break;}}}}}}}}

小结 

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

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

 


http://www.ppmy.cn/news/1361022.html

相关文章

【设计模式】01-装饰器模式Decorator

作用&#xff1a;在不修改对象外观和功能的情况下添加或者删除对象功能&#xff0c;即给一个对象动态附加职能 装饰器模式主要包含以下角色。 抽象构件&#xff08;Component&#xff09;角色&#xff1a;定义一个抽象接口以规范准备接收附加责任的对象。具体构件&#xff08…

Git diff Word 文档

前言 前段时间用 nodeJS 写了一个提交代码的工具&#xff0c;开发过程中在认证部分遇到了一些小问题&#xff0c;于是就想看看官方的文档中有没有什么说明之类的&#xff0c;没想到文档中的内容十分丰富&#xff0c;除了解释了 git 相关的原理外&#xff0c;还学到了很多有用的…

多层的二叉树结构如何快速写出其前序、中序、后序。

问题描述&#xff1a;多层的二叉树结构如何快速写出其前序、中序、后序。 问题解答&#xff1a;从顶部的二叉树&#xff0c;依次往下写&#xff0c;先写出第一层的二叉树&#xff0c;然后再写第二层的二叉树。当然按照的规则还是前序根左右&#xff0c;中序左根右&#xff0c;后…

五种多目标优化算法(MOGWO、MOJS、NSWOA、MOPSO、MOAHA)性能对比(提供MATLAB代码)

一、5种多目标优化算法简介 1.1MOGWO 1.2MOJS 1.3NSWOA 1.4MOPSO 1.5MOAHA 二、5种多目标优化算法性能对比 为了测试5种算法的性能将其求解9个多目标测试函数&#xff08;zdt1、zdt2 、zdt3、 zdt4、 zdt6 、Schaffer、 Kursawe 、Viennet2、 Viennet3&#xff09;&#xff0…

CVE-2023-44313 Apache ServiceComb Service-Center SSRF 漏洞研究

本次项目基于go语言&#xff08;本人不精通&#xff09;&#xff0c;虽不是java web框架了 &#xff0c;但搭建web服务的框架一些思想理念却是通用的&#xff0c;我们由此可以得到一些蛛丝马迹....... 目录 漏洞简介 漏洞分析 漏洞复现 漏洞简介 Apache ServiceComb Servi…

构建一个动态数据可视化仪表板

一、引言 在现代Web开发中&#xff0c;JavaScript不仅是网页交互的核心&#xff0c;而且已经成为实现复杂前端功能的重要工具。在本篇博客中&#xff0c;我将展示如何使用JavaScript构建一个动态数据可视化仪表板。该仪表板能够实时展示从服务器获取的数据&#xff0c;并通过图…

Java最全面试总结——6.Springboot篇

1、为什么要用SpringBoot Spring Boot 优点非常多&#xff0c;如&#xff1a; 一、独立运行 Spring Boot而且内嵌了各种servlet容器&#xff0c;Tomcat、Jetty等&#xff0c;现在不再需要打成war包部署到容器 中&#xff0c;Spring Boot只要打成一个可执行的jar包就能独立运行…

.Net 8.0 新的变化

.NET 8 是微软于2021年8月24日宣布的下一代编程语言和框架&#xff0c;它是 .NET 宇宙的一部分&#xff0c;与 C# (Common Language Infrastructure) 紧密集成。.NET 8 引入了许多新功能&#xff0c;如原生编译、值类型 (Value Types)、结构化并发 (structured concurrency) 和…