Pechkin使用心得(二)

完成Pechkin使用心得(一)的内容后。下面正式进入代码实现的阶段。

在项目中引用Pechkin.dll与Pechkin.Synchronized.dll后编写以下示例代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
using System.Web;
using System.Net;
using Pechkin;
using Pechkin.Synchronized; 

namespace HTMLtoPDF
{

  public partial class Form1 : Form

  {
    public Form1()
    {
      InitializeComponent();
    }    

    private void button1_Click(object sender, EventArgs e)
    {
      ConverHTMLtoPDF("...Place some html web page code here...");
    }

    private void ConverHTMLtoPDF(string html)
    {
      SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig()

        .SetMargins(new Margins() { Left = 0, Right = 0, Top = 0, Bottom = 0 }) //设置边距

        .SetPaperOrientation(true) //设置纸张方向为横向
        .SetPaperSize(ConvertToHundredthsInch(50), ConvertToHundredthsInch(100))); //设置纸张大小(使用者可以根据自己的需求设置。这里的50代表,100代表)

      ObjectConfig oc = new ObjectConfig();

      oc.SetPrintBackground(true).SetLoadImages(true).Header.SetHtmlContent(WebPageUri);  

      //以上设置十分重要:

      //SetPrintBackground(true)是显示样式所必须的(例如令设置有颜色的<div>能在PDF中显示出来)。

      //SetLoadImages(true)令PDF可以加载图片。由于Pechkin是封装wkhtmltopdf。wkhtmltopdf是不能识别相对路径的图片文件的。所以HTML内的所有图片路径都不能使用相对路径必须使用绝对路径

      //.Header.SetHtmlContent(WebPageUri)是使用一个网页内容来设置PDF的页眉。

      byte[] buf = sc.Convert(oc, html);

      if (buf == null)
      {
         MessageBox.Show("Error converting!");
         return;
      }

      try
      {
         string fn = "H:\\Learn\\Myself\\Test\\HTMLtoPDF\\file_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
         FileStream fs = new FileStream(fn, FileMode.Create);
         fs.Write(buf, 0, buf.Length);
         fs.Close();
      }
      catch { }

    }

  }

}

下面是生成的一个PDF例子。效果还是不错的

 不设置SetPrintBackground(true)就会得到以下效果(<div>有填充颜色的都没有填充颜色):

 

代码实现就到这里结束了。 

 

引用以下网站部分内容:

http://www.knowsky.com/898441.html

http://www.cnblogs.com/yjmyzz/p/3286604.html

原文地址:https://www.cnblogs.com/MatrixBlogs/p/5958816.html