C#使用phantomjs对网页截图

        众所周知,现在的主流浏览器使用的主要是三大内核,一是以IE为代表的Trident内核,二是以Google Chrome为代表的webkit内核,三是以火狐为代表的Gecko内核。一般来讲,C#网页截图使用C#控件中的WebBroswer比较多,这样的帖子挺多的,也十分省事。但今天要分享的是使用phantomjs对网页截图,phantomjs是以webkit为内核的无头浏览器,就是没有界面。

一、下载phantomjs.exe

下载地址:http://phantomjs.org/download.html

二、编写js文件

screenshot.js文件

var page = require('webpage').create(), system = require('system'), address, output, size;

if (system.args.length < 3 || system.args.length > 5) {
    phantom.exit(1);
} else {
    address = system.args[1];
    output = system.args[2];
    //定义宽高
    page.viewportSize = {
        width : 1000,
        height : 800
    };
    page.open(address, function(status) {
        var bb = page.evaluate(function() {
            return document.getElementsByTagName('html')[0].getBoundingClientRect();
        });
        page.clipRect = {
            top : bb.top,
            left : bb.left,
            width : bb.width,
            height : bb.height
        };
        window.setTimeout(function() {
            page.render(output);
            page.close();
            console.log('渲染成功...');
            phantom.exit();
        }, 1000);
    });
}
 

 
 

解释一下:

1、page.viewportSize是定义浏览器的宽和高;

2、page.clipRect就是在指定截图区域的宽和高以及距浏览器左边和上边的距离,代码中的bb.top与bb.left代表的就是浏览器的边缘,建议指定截图区域距离上边距离的时候以bb.top+50 这种形式来指定,左边亦如此;

3、window.setTimeout是用来指定浏览器加载时间的。

三、进行截图

1、首先将phantomjs.exe与screenshot.js文件放在解决方案中(我的是这样放的)

2、编写代码进行截图

WebHelper.cs

using System;
using System.Windows.Forms; 
using System.Threading;
using System.Diagnostics;
using System.IO;

namespace MyWeb.CommonMVC
{
    public class WebHelper
    {
        private string link;
        private string path;
        private string serverPath;
        public WebHelper(string link,string path,string serverpath)
        {
            this.link = link;
            this.path = path;
            this.serverPath = serverpath;
        }
        /// <summary>
        /// 启用新线程
        /// </summary>
        public void GetImg()
        {
            var m_thread = new Thread(GetHtmlImage);
            m_thread.SetApartmentState(ApartmentState.STA);
            m_thread.Start();
            m_thread.Join();
        }
        /// <summary>
        /// 调用截图方法,然后进行等待,一直到图片生成为止
        /// </summary>
        private void GetHtmlImage()
        {

            GetImg1(link, path, serverPath);
            while (true)
            {
                if (File.Exists(serverPath+"\\"+path))
                {
                    break;
                }
                DateTime current = DateTime.Now;
                while (current.AddMilliseconds(2000) > DateTime.Now)
                {
                    Application.DoEvents();//转让控制权
                }
            }
        }
        /// <summary>
        /// 进行截图
        /// </summary>
        /// <param name="links">截图网页链接</param>
        /// <param name="path">截图生成的文件存放的路径及其文件名</param>
        /// <param name="serverPath">phantomjs.exe与screenshot.js所在目录的路径</param>
        /// <returns></returns>
        public bool GetImg1(string links, string path, string serverPath)
        {
            try
            {
                Process p = new Process();
                p.StartInfo.FileName = serverPath + @"\phantomjs.exe";
                // p.StartInfo.FileName = @"E:\SoftWare\phantomjs-2.1.1-windows\bin\phantomjs.exe";
                p.StartInfo.WorkingDirectory = serverPath + @"\";
                p.StartInfo.Arguments = string.Format(serverPath + @"\screenshot.js " + links + " " + path);

                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                p.Start();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }
    }
}


在程序中调用方法如下:

四、总结

      用于网页截图的方法有很多种,之前使用过html2canvas在前端直接截图,但令人苦恼的是网页中包含地图,涉及跨域问题,较难解决;后来改用WeBroswer,又因为他使用的内核是IE7,致使加载地图时有一些的不兼容问题,最终选择phantomjs也是经朋友推荐,希望给大家帮助,不足之处,敬请谅解!


发布了3 篇原创文章 · 获赞 8 · 访问量 6515

猜你喜欢

转载自blog.csdn.net/olifchou/article/details/78740362