C#使用wkhtmltopdf.exe,HTML页面转化为PDF文档

此文用来记录使用wkhtmltopdf.exe在C#代码中将html转换为PDF的过程:

1,在http://wkhtmltopdf.org/downloads.html 下载wkhtmltopdf.exe的安装文件,分为32位和64为,可以根据自己系统类型选择

2,安装wkhtmltopdf.exe,成功安装

3,在到安装好的bin文件中,找到wkhtmltopdf.exe文件,将该文档放在自己新建项目的一个文件夹中,将在代码中使用它。

4,可以将安装的wkhtmltopdf从电脑中卸除,只要保证项目文件夹中存在刚放进去的文件即可(可以随自己意愿卸除或者不卸除,可以卸载这也是我后来发现的)

 

好了,下面开始正式写代码了:

using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Linkin.Web.HttpHandler
{
    public class ExportToPDF
    {
        /// <summary>  
        /// HTML生成PDF  
        /// </summary>  
        /// <param name="url">地址</param>  
        /// <param name="path">PDF存放路径</param>  
        public static void HtmlToPdf(string urlPath, string fileName)
        {
            //获取当前项目的路径
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string savepath = path + fileName + ".pdf";//最终保存
            string url = urlPath;
            try
            {
                if (!string.IsNullOrEmpty(url) || !string.IsNullOrEmpty(savepath))
                {
                    System.Diagnostics.Process p = new System.Diagnostics.Process();

                    string dllstr = path + "App_Data\\wkhtmltopdf.exe";
                    if (System.IO.File.Exists(dllstr))
                    {
                        p.StartInfo.FileName = dllstr;

                        p.StartInfo.Arguments = " \"" + url + "\"  \"" + savepath + "\"";

                        p.StartInfo.UseShellExecute = false;

                        p.StartInfo.RedirectStandardInput = true;

                        p.StartInfo.RedirectStandardOutput = true;

                        p.StartInfo.RedirectStandardError = true;

                        p.StartInfo.CreateNoWindow = true;

                        p.Start();

                        p.WaitForExit();
                        try
                        {
                            //添加水印功能
                            var WaterFilePath = path + fileName + "2.pdf";
                            //var image = path + "Content\\images\\logo2.png";                          
                            var flag = setWatermark(savepath, WaterFilePath, "金领英才网");
                            var exportFile = "";
                            if (flag)
                                exportFile = WaterFilePath;
                            else
                                exportFile = savepath;

                            FileStream fs = new FileStream(exportFile, FileMode.Open);
                            byte[] file = new byte[fs.Length];
                            fs.Read(file, 0, file.Length);
                            fs.Close();

                            if (flag)
                                System.IO.File.Delete(WaterFilePath);//删除文件                            
                            System.IO.File.Delete(savepath);//删除文件

                            System.Web.HttpContext.Current.Response.Clear();
                            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".pdf");//強制下載
                            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
                            System.Web.HttpContext.Current.Response.BinaryWrite(file);

                        }
                        catch (Exception ee)
                        {
                            throw new Exception(ee.ToString());

                        }
                    }

                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

        /// <summary>
        /// 添加普通偏转角度文字水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="waterMarkName"></param>
        /// <param name="permission"></param>
        public static bool setWatermark(string inputfilepath, string outputfilepath, string waterMarkName)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                int total = pdfReader.NumberOfPages + 1;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
                float width = psize.Width;
                float height = psize.Height;
                PdfContentByte content;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState gs = new PdfGState();
                for (int i = 1; i < total; i++)
                {
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                    //透明度
                    gs.FillOpacity = 0.3f;
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);
                    //开始写入文本
                    content.BeginText();
                    content.SetColorFill(iTextSharp.text.BaseColor.LIGHT_GRAY);
                    content.SetFontAndSize(font, 100);
                    content.SetTextMatrix(0, 0);
                    content.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, waterMarkName, width / 2 - 50, height / 2 - 50, 55);
                    //content.SetColorFill(BaseColor.BLACK);
                    //content.SetFontAndSize(font, 8);
                    //content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);
                    content.EndText();
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
                return false;
            }
            finally
            {

                if (pdfStamper != null)
                    pdfStamper.Close();

                if (pdfReader != null)
                    pdfReader.Close();
            }
        }
    

 调用代码:

 Linkin.Web.HttpHandler.ExportToPDF.HtmlToPdf("http://www.cnblogs.com/ITGirl00/", "mypdf");

 生成pdf为:

 

===小小提示===

(1)使用wkhtmltopdf时,PDF保存的文件夹不能有非Ansi字符,如中文、日文等,且转换gb2312、韩文charset、日文charset等非utf-8\ansi等网页时,会出现乱码

(2)网页上图片无法正确显示是由于图片有链接

 

 

 

posted @ 2014-07-12 09:39  细数青春  阅读(1759)  评论(4编辑  收藏  举报