天天看點

C# 将 HTML 轉換為圖檔或 PDF

首先是把 HTML 轉換為圖檔。

C# 将 HTML 轉換為圖檔或 PDF
C# 将 HTML 轉換為圖檔或 PDF

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标簽。如下:

C# 将 HTML 轉換為圖檔或 PDF
C# 将 HTML 轉換為圖檔或 PDF
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();
        }
    }      

然後把圖檔轉換為PDF,這裡需要用到 iTextSharp.dll 這個元件。

C# 将 HTML 轉換為圖檔或 PDF
C# 将 HTML 轉換為圖檔或 PDF
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();
            }
        }
    }      

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

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

C# 将 HTML 轉換為圖檔或 PDF
C# 将 HTML 轉換為圖檔或 PDF
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();
        }
        
    }