C#怎麼將 HTML轉換為圖片或 PDF?

來源:互聯網
上載者:User
首先是把 HTML 轉換為圖片。

public partial class Form1 : Form    {public Form1()        {            InitializeComponent();        }        WebBrowser webBrowser = null;public void ConvertToImg()        {            webBrowser = new WebBrowser();//是否顯式捲軸webBrowser.ScrollBarsEnabled = false;//載入HTML頁面的地址webBrowser.Navigate("");            //頁面載入完成執行事件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;//載入 htmlwebBrowser.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;//載入 htmlwebBrowser.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);//建立PDFFileStream 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);//直接設定htmlint docID = doc.AddHtml(html);//設定URL//int docID = doc.AddImageUrl("");//設定字型doc.AddFont("Arial");while (true)            {//判斷是否還有內容if (!doc.Chainable(docID))                {break;                }//如果還有內容就添加一頁doc.Page = doc.AddPage();//根據ID新增內容並返回頁面上該內容對應的新IDdocID = 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
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.