1. 程式人生 > >C# 將 HTML 轉換為圖片或 PDF

C# 將 HTML 轉換為圖片或 PDF

ont gif completed 字段 sed pad cli 滾動條 lose

首先是把 HTML 轉換為圖片。

技術分享
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        WebBrowser webBrowser = null;

        public void ConvertToImg()
        {
            webBrowser = new WebBrowser();

            //是否顯式滾動條
            webBrowser.ScrollBarsEnabled = false
; //加載HTML頁面的地址 webBrowser.Navigate("http://www.baidu.com"); //頁面加載完成執行事件 webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted); } private void webBrowser_DocumentCompleted(object
sender, EventArgs e)//這個就是當網頁載入完畢後要進行的操作 { //獲取解析後HTML的大小 System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle; int width = rectangle.Width; int height = rectangle.Height; //設置解析後HTML的可視區域 webBrowser.Width = width; webBrowser.Height
= height; Bitmap bitmap = new System.Drawing.Bitmap(width, height); webBrowser.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, width, height)); //設置圖片文件保存路徑和圖片格式,格式可以自定義 string filePath = AppDomain.CurrentDomain.BaseDirectory + "../../SaveFIle/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"; bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); } private void button1_Click(object sender, EventArgs e) { ConvertToImg(); } }
View Code

上面這種方法是解析指定URL地址的HTML,然後轉換為圖片。當然,也可以直接寫一些HTML標簽。如下:

技術分享
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        WebBrowser webBrowser = null;
        public void ConvertToImg()
        {
            string html = "<div><table border = \"1\" cellspacing = \"0\" cellpadding = \"3\" style = \"text-align:center;\"><tr><th style = \"width:60px;\">字段1</th><th style = \"width:60px;\">字段2</th><th style = \"width:60px;\">字段3</th></tr><tr style = \"color:green;\"><td>小明</td><td>22</td><td>185</td></tr><tr style = \"color:red;\"><td>小青</td><td>21</td><td>170</td></tr></table></div>";

            webBrowser = new WebBrowser();

            //是否顯式滾動條
            webBrowser.ScrollBarsEnabled = false;

            //加載 html
            webBrowser.DocumentText = html;
            
            //頁面加載完成執行事件
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
        }

        private void webBrowser_DocumentCompleted(object sender, EventArgs e)//這個就是當網頁載入完畢後要進行的操作
        {
            //獲取解析後HTML的大小
            System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle;
            int width = rectangle.Width;
            int height = rectangle.Height;

            //設置解析後HTML的可視區域
            webBrowser.Width = width;
            webBrowser.Height = height;

            Bitmap bitmap = new System.Drawing.Bitmap(width, height);
            webBrowser.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, width, height));

            //設置圖片文件保存路徑和圖片格式,格式可以自定義
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "../../SaveFIle/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
            bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ConvertToImg();
        }
    }
View Code

然後把圖片轉換為PDF,這裏需要用到 iTextSharp.dll 這個組件。

技術分享
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        WebBrowser webBrowser = null;
        public void ConvertToImg()
        {
            string html = "<div><table border = \"1\" cellspacing = \"0\" cellpadding = \"3\" style = \"text-align:center;\"><tr><th style = \"width:60px;\">字段1</th><th style = \"width:60px;\">字段2</th><th style = \"width:60px;\">字段3</th></tr><tr style = \"color:green;\"><td>小明</td><td>22</td><td>185</td></tr><tr style = \"color:red;\"><td>小青</td><td>21</td><td>170</td></tr></table></div>";

            webBrowser = new WebBrowser();

            //是否顯式滾動條
            webBrowser.ScrollBarsEnabled = false;

            //加載 html
            webBrowser.DocumentText = html;
            
            //頁面加載完成執行事件
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
        }

        private void webBrowser_DocumentCompleted(object sender, EventArgs e)//這個就是當網頁載入完畢後要進行的操作
        {
            //獲取解析後HTML的大小
            System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle;
            int width = rectangle.Width;
            int height = rectangle.Height;

            //設置解析後HTML的可視區域
            webBrowser.Width = width;
            webBrowser.Height = height;

            Bitmap bitmap = new System.Drawing.Bitmap(width, height);
            webBrowser.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, width, height));

            //設置圖片文件保存路徑和圖片格式,格式可以自定義
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "../../SaveFIle/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
            bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);

            //創建PDF
            FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "../../SaveFIle/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf", FileMode.Create);

            byte[] result = CreatePDF(bitmap, width, height);

            fileStream.Write(result, 0, result.Length);

            fileStream.Close();
            fileStream.Dispose();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ConvertToImg();
        }

        public byte[] CreatePDF(Bitmap bitmap, int width, int height)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                Document doc = new Document(new iTextSharp.text.Rectangle(0, 0, width, height), 3, 3, 3, 3);    // 左右上下

                PdfWriter writer = PdfWriter.GetInstance(doc, ms);

                writer.CloseStream = false;

                doc.Open();

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Png);

                img.ScalePercent(100);      // 放縮比例

                doc.Add(img);       // 添加圖片對像
                doc.Close();

                return ms.ToArray();
            }
        }
    }
View Code

不過這種生成圖片之後再轉成PDF,會造成像素的丟失,所以看起來要比圖片模糊一點。

還有一種辦法就是直接生成PDF,這裏需要安裝 ABCpdf。不過,這個是收費的。。。

技術分享
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void ConvertToPDF()
        {
            string html = "<div><table border = \"1\" cellspacing = \"0\" cellpadding = \"3\" style = \"text-align:center;\"><tr><th style = \"width:60px;\">字段1</th><th style = \"width:60px;\">字段2</th><th style = \"width:60px;\">字段3</th></tr><tr style = \"color:green;\"><td>小明</td><td>22</td><td>185</td></tr><tr style = \"color:red;\"><td>小青</td><td>21</td><td>170</td></tr></table></div>";

            //創建一個Doc對象
            Doc doc = new Doc();

            //Rect默認是文檔整個頁面大小,這裏的Inset表示將Rect左右留出15的空白,上下留出20的空白
            doc.Rect.Inset(15, 20);

            //直接設置html
            int docID = doc.AddHtml(html);

            //設置URL
            //int docID = doc.AddImageUrl("http://www.baidu.com");

            //設置字體
            doc.AddFont("Arial");

            while (true)
            {
                //判斷是否還有內容
                if (!doc.Chainable(docID))
                {
                    break;
                }

                //如果還有內容就添加一頁
                doc.Page = doc.AddPage();

                //根據ID添加內容並返回頁面上該內容對應的新ID
                docID = doc.AddImageToChain(docID);
            }

            string filePath = AppDomain.CurrentDomain.BaseDirectory + "../../SaveFIle/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";

            doc.Save(filePath);

            doc.Clear();
            doc.Dispose();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            ConvertToPDF();
        }
        
    }
View Code

C# 將 HTML 轉換為圖片或 PDF