NetCore Html轉Image


using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace ConsoleApp_NetCore
{
    class Program
    {
        static void Main(string[] args)
        {
            Index();
            Console.ReadKey();
        }

        static void Index()
        {
            HtmlConvertToImg("https://www.baidu.com", @"D:\文件\word\123.jpg");
        }
        
        /// <summary>
        /// HTML文本內容轉換為Img
        /// </summary>
        /// <param name="strHtml">HTML文本內容</param>
        /// <param name="savePath">Img文件保存的路徑</param>
        /// <returns></returns>
        static bool HtmlTextConvertToImg(string strHtml, string savePath)
        {
            bool flag = false;
            try
            {
                string htmlPath = HtmlTextConvertFile(strHtml);

                flag = HtmlConvertToImg(htmlPath, savePath);
                File.Delete(htmlPath);
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// HTML轉換為Img
        /// </summary>
        /// <param name="htmlPath">可以是本地路徑,也可以是網絡地址</param>
        /// <param name="savePath">PDF文件保存的路徑</param>
        /// <returns></returns>
        static bool HtmlConvertToImg(string htmlPath, string savePath)
        {
            bool flag = false;
            CheckFilePath(savePath);

            ///這個路徑為程序集的目錄,因為我把應用程序 wkhtmltopdf.exe 放在了程序集同一個目錄下
            string exePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "wkhtmltopdf.exe";
            exePath = @"C:\Users\T480\.nuget\packages\netcorehtmltoimage\1.0.1.4\contentFiles\any\netstandard2.0\wkhtmltoimage.exe";
            if (!File.Exists(exePath))
            {
                throw new Exception("No application wkhtmltopdf.exe was found.");
            }

            try
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = exePath;
                processStartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
                processStartInfo.UseShellExecute = false;
                processStartInfo.CreateNoWindow = true;
                processStartInfo.RedirectStandardInput = true;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardError = true;
                processStartInfo.Arguments = GetArguments(htmlPath, savePath);

                Process process = new Process();
                process.StartInfo = processStartInfo;
                process.Start();
                process.WaitForExit();

                // 用於查看是否返回錯誤信息
                //StreamReader srone = process.StandardError;
                //StreamReader srtwo = process.StandardOutput;
                //string ss1 = srone.ReadToEnd();
                //string ss2 = srtwo.ReadToEnd();
                //srone.Close();
                //srone.Dispose();
                //srtwo.Close();
                //srtwo.Dispose();

                process.Close();
                process.Dispose();

                flag = true;
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 獲取命令行參數
        /// </summary>
        /// <param name="htmlPath"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        static string GetArguments(string htmlPath, string savePath)
        {
            if (string.IsNullOrEmpty(htmlPath))
            {
                throw new Exception("HTML local path or network address can not be empty.");
            }

            if (string.IsNullOrEmpty(savePath))
            {
                throw new Exception("The path saved by the Img document can not be empty.");
            }

            StringBuilder stringBuilder = new StringBuilder();
            //stringBuilder.Append(" --crop-w 410 ");        //截圖寬度410px
            //stringBuilder.Append(" --width 410 ");        //瀏覽器模擬寬度410px
            stringBuilder.Append(" --quality 100 ");         //圖片質量(這個值越大,圖片質量越高,當然文件也會比較大)
            stringBuilder.Append(" " + htmlPath + " ");       //本地 HTML 的文件路徑或網頁 HTML 的URL地址
            stringBuilder.Append(" " + savePath + " ");       //生成的文檔的保存路徑
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 驗證保存路徑
        /// </summary>
        /// <param name="savePath"></param>
        static void CheckFilePath(string savePath)
        {
            string ext = string.Empty;
            string path = string.Empty;
            string fileName = string.Empty;

            ext = Path.GetExtension(savePath);
            if (string.IsNullOrEmpty(ext) || (ext.ToLower() != ".jpg" && ext.ToLower() != ".jpeg" && ext.ToLower() != ".png"))
            {
                throw new Exception("Extension error:This method is used to generate Img files.");
            }

            fileName = Path.GetFileName(savePath);
            if (string.IsNullOrEmpty(fileName))
            {
                throw new Exception("File name is empty.");
            }

            try
            {
                path = savePath.Substring(0, savePath.IndexOf(fileName));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch
            {
                throw new Exception("The file path does not exist.");
            }
        }

        /// <summary>
        /// HTML文本內容轉HTML文件
        /// </summary>
        /// <param name="strHtml">HTML文本內容</param>
        /// <returns>HTML文件的路徑</returns>
        static string HtmlTextConvertFile(string strHtml)
        {
            if (string.IsNullOrEmpty(strHtml))
            {
                throw new Exception("HTML text content cannot be empty.");
            }

            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"html\";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string fileName = path + DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 10000) + ".html";
                FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default);
                streamWriter.Write(strHtml);
                streamWriter.Flush();

                streamWriter.Close();
                streamWriter.Dispose();
                fileStream.Close();
                fileStream.Dispose();
                return fileName;
            }
            catch
            {
                throw new Exception("HTML text content error.");
            }
        }

    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM