SoFunction
Updated on 2025-03-07

Use C# to save web page content as pictures and generate compressed packages

Application scenarios

In the project function of a job resume printing, we need to obtain results and batch export files of the specified format based on certain query conditions. There may be many exported formats, such as WORD format, EXCEL format, PDF format, etc. The implementation method is to output by setting the corresponding template. The actual situation is that the content of the resume is flexibly set, without a fixed format, and the number of templates is not fixed.

Through dynamic page technology, web page content output after resume configuration can be achieved, but the production of corresponding templates will encounter problems with development efficiency and service follow-up. In order to ensure the output as it is, the compromise and simple solution is to convert the dynamically output page into an image format.

Implement code

Create a UrlToImage class, pass the specified URL when creating an instance, and call the SaveToImageFile (string outputFilename) method. This method just passes the file name parameter to be output.

The call sample code is as follows:

string url = "https://" +  + "/";
UrlToImage uti = new UrlToImage(url);
bool irv = ( + "\\");
if(bool==false){
    ("save failed.");
    ();
}

The class and implementation code are as follows:

    public class UrlToImage
    {
        private  Bitmap m_Bitmap;
        private string m_Url;
        private string m_FileName = ;
        int initheight = 0;
 
        public UrlToImage(string url)
        {
            // Without file
            m_Url = url;
        }
 
        public UrlToImage(string url, string fileName)
        {
            // With file
            m_Url = url;
            m_FileName = fileName;
        }
 
        public Bitmap Generate()
        {
            // Thread
            var m_thread = new Thread(_Generate);
            m_thread.SetApartmentState();
            m_thread.Start();
            m_thread.Join();
            return m_Bitmap;
        }
        public bool SaveToImageFile(string filename)
        {
            Bitmap bt=Generate();
            if (bt == null)
            {
                return false;
            }
            (filename);
            return (filename);
        }
        private void _Generate()
        {
            var browser = new WebBrowser { ScrollBarsEnabled = false };
             = true;
            initheight = 0;
            (m_Url);
             += WebBrowser_DocumentCompleted;
 
            while ( != )
            {
                ();
            }
 
            ();
        }
 
        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // Capture
            var browser = (WebBrowser)sender;
             = new Size(, );
             = false;
            m_Bitmap = new Bitmap(, );
            ();
            (m_Bitmap, );
 
            // Save as file?
            if (m_FileName.Length > 0)
            {
                // Save
                m_Bitmap.SaveJPG100(m_FileName);
            }
            if (initheight == )
            {
                 -= new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            }
            initheight = ;
        }
    }

Generate a compressed package

For batch generated image files, we can generate compressed packages to provide customers with download functions. The compression function refers to creating an instance of the ZipCompress class, the ZipDirectory(zippath, zipfile, password) method. The parameters that need to be provided include the compressed directory, the generated compressed file name, and the opening password of the compressed package.

The sample code is as follows:

    string zippath =  + "\\des\\" ;
    if (!(zippath))
    {
        (zippath);
    }
    string zipfile =  + "\\des\\";
    ZipCompress allgzip = new ZipCompress();
     alldi = new (zippath);
    string password = "123456";
 
    (zippath, zipfile, password);
    //The following is to clear the directory and files after generating the compressed package    string[] allfs = (zippath);
    for (int i = 0; i < ; i++)
    {
        (allfs[i]);
    }
    (zippath);  

The class and implementation code are as follows:

 public class ZipCompress
    {
        
        public  byte[] Compress(byte[] inputBytes)
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                using (GZipStream zipStream = new GZipStream(outStream, , true))
                {
                    (inputBytes, 0, );
                    (); //It is very important, it must be closed, otherwise it will not be decompressed correctly                    return ();
                }
            }
        }
 
        public  byte[] Decompress(byte[] inputBytes)
        {
 
            using (MemoryStream inputStream = new MemoryStream(inputBytes))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    using (GZipStream zipStream = new GZipStream(inputStream, ))
                    {
                        (outStream);
                        ();
                        return ();
                    }
                }
 
            }
        }
        public  string Compress(string input)
        {
            byte[] inputBytes = (input);
            byte[] result = Compress(inputBytes);
            return Convert.ToBase64String(result);
        }
        public  string Decompress(string input)
        {
            byte[] inputBytes = Convert.FromBase64String(input);
            byte[] depressBytes = Decompress(inputBytes);
            return (depressBytes);
        }
        public  void Compress(DirectoryInfo dir)
        {
            foreach (FileInfo fileToCompress in ())
            {
                Compress(fileToCompress);
            }
        }
        public  void Decompress(DirectoryInfo dir)
        {
            foreach (FileInfo fileToCompress in ())
            {
                Decompress(fileToCompress);
            }
        }
        public  void Compress(FileInfo fileToCompress)
        {
            using (FileStream originalFileStream = ())
            {
                if ((() & ) !=  &  != ".gz")
                {
                    using (FileStream compressedFileStream = ( + ".gz"))
                    {
                        using (GZipStream compressionStream = new GZipStream(compressedFileStream, ))
                        {
                            (compressionStream);
                        }
                    }
                }
            }
        }
        public  void Decompress(FileInfo fileToDecompress,string desfilename="")
        {
            using (FileStream originalFileStream = ())
            {
                string currentFileName = ;
                string newFileName = ( - );
                if (desfilename != "")
                {
                    newFileName = desfilename;
                }
 
                using (FileStream decompressedFileStream = (newFileName))
                {
                    using (GZipStream decompressionStream = new GZipStream(originalFileStream, ))
                    {
                        (decompressedFileStream);
                    }
                }
            }
        }
 
 
        
        public  void ZipDirectory(string folderToZip, string zipedFileName,string password)
        {
            ZipDirectory(folderToZip, zipedFileName,(password==""?:password), true, , , true);
        }
 
 
 
        public  void ZipDirectory(string folderToZip, string zipedFileName, string password, bool isRecurse, string fileRegexFilter, string directoryRegexFilter, bool isCreateEmptyDirectories)
        {
             FastZip fastZip = new FastZip();
             = isCreateEmptyDirectories;
             = password;
            (zipedFileName, folderToZip, isRecurse, fileRegexFilter, directoryRegexFilter);
       
        }
        public void UnZipDirectory(string zipedFileName, string targetDirectory, string password,string fileFilter=null)
        {
            FastZip fastZip = new FastZip();
             = password;
            (zipedFileName, targetDirectory,fileFilter);
 
        }
 
 
        public void UnZip(string zipFilePath, string unZipDir)
        {
           
            if (zipFilePath == )
            {
                throw new Exception("The compressed file cannot be empty!");
            }
            if (!(zipFilePath))
            {
                throw new FileNotFoundException("The compressed file does not exist!");
            }
            // When the decompressed folder is empty, the default is the same as the compressed file in the same level directory as the compressed file, and the folder with the same name as the compressed file is            if (unZipDir == )
                unZipDir = ((zipFilePath), (zipFilePath));
            if (!("/"))
                unZipDir += "/";
            if (!(unZipDir))
                (unZipDir);
 
            using (var s = new ZipInputStream((zipFilePath)))
            {
 
                ZipEntry theEntry;
                while ((theEntry = ()) != null)
                {
                    string directoryName = ();
                    string fileName = ();
                    if (!(directoryName))
                    {
                        (unZipDir + directoryName);
                    }
                    if (directoryName != null && !("/"))
                    {
                    }
                    if (fileName != )
                    {
                        using (FileStream streamWriter = (unZipDir + ))
                        {
 
                            int size;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = (data, 0, );
                                if (size > 0)
                                {
                                    (data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
 
    }

summary

For the generated image files, we can also combine other API applications to determine whether the image is PSed to improve and expand the functions of the application. In addition, for the dynamic pages you are accessed, it is recommended to use access control. Only users who log in normally or provide access tokens can generate result images to ensure the security of the data.

This is the article about using C# to save web content as pictures and generate compressed packages. For more related C# web content as pictures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!