phantomjs html to PDF

*.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.IO;

/// <summary>
///PDFCommon 的摘要说明
/// </summary>
public class PDFCommon
{
	public PDFCommon()
	{
		
	}
    public static string CreatePDF(string url)
    {
        string fileNameWithOutExtention = Guid.NewGuid().ToString();
        string path = System.Web.HttpContext.Current.Server.MapPath(@"~\bin\phantomjs\");
        //string paths = System.Web.HttpContext.Current.Server.MapPath(@"~\chartPdfFile");
        string savePath = Path.Combine(@"D:/", string.Format("{0}.pdf", Guid.NewGuid()));
        string filePath = Path.Combine(path, "phantomjs.exe");
        string jsPath = Path.Combine(path, "generate_pdf.js");
        string argument = string.Format(" --ignore-ssl-errors=yes  {0} \"{1}\" {2}", jsPath, url, savePath);
        using (System.Diagnostics.Process exep = new System.Diagnostics.Process())
        {
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.FileName = filePath;
            startInfo.Arguments = argument;
            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            exep.StartInfo = startInfo;
            exep.Start();
            exep.WaitForExit();
        }
        return savePath;
    }
}

*.js

// This file is NOT a browser-run javascript but PhantonJS script
var system = require('system');
var address = system.args[1];
var output = system.args[2];
var page = require('webpage').create();
page.paperSize = {
  format: 'A4',
  orientation: 'landscape',
  border: '1cm'
};
page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        window.setTimeout(function () {
            // Remove all low-opacity paths. see PhantomJS  issue #364 
            page.evaluate(function () {
                var paths = document.getElementsByTagName("path");
                for (var i = paths.length - 1; i >= 0; i--) {
                    var path = paths[i];
                    var strokeOpacity = path.getAttribute('stroke-opacity');
                    if (strokeOpacity != null && strokeOpacity < 0.2)
                        path.parentNode.removeChild(path);
                }
            });
            page.render(output);
            phantom.exit();
        }, 5000);
    }
});


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值