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


免責聲明!

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



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