C#將HTML轉(zhuǎn)換為圖片或PDF的方法

小編給大家分享一下C#將HTML轉(zhuǎn)換為圖片或PDF的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

成都創(chuàng)新互聯(lián)公司長(zhǎng)期為數(shù)千家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為松嶺企業(yè)提供專業(yè)的成都網(wǎng)站建設(shè)、網(wǎng)站制作,松嶺網(wǎng)站改版等技術(shù)服務(wù)。擁有10多年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。

首先是把 HTML 轉(zhuǎn)換為圖片。


public partial class Form1 : Form
    {public Form1()
        {
            InitializeComponent();
        }

        WebBrowser webBrowser = null;public void ConvertToImg()
        {
            webBrowser = new WebBrowser();//是否顯式滾動(dòng)條webBrowser.ScrollBarsEnabled = false;//加載HTML頁(yè)面的地址webBrowser.Navigate("");            //頁(yè)面加載完成執(zhí)行事件webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
        }private void webBrowser_DocumentCompleted(object sender, EventArgs e)//這個(gè)就是當(dāng)網(wǎng)頁(yè)載入完畢后要進(jìn)行的操作        {//獲取解析后HTML的大小System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle;int width = rectangle.Width;int height = rectangle.Height;//設(shè)置解析后HTML的可視區(qū)域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));//設(shè)置圖片文件保存路徑和圖片格式,格式可以自定義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,然后轉(zhuǎn)換為圖片。當(dāng)然,也可以直接寫(xiě)一些HTML標(biāo)簽。如下:


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();//是否顯式滾動(dòng)條webBrowser.ScrollBarsEnabled = false;//加載 htmlwebBrowser.DocumentText = html;            //頁(yè)面加載完成執(zhí)行事件webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
        }private void webBrowser_DocumentCompleted(object sender, EventArgs e)//這個(gè)就是當(dāng)網(wǎng)頁(yè)載入完畢后要進(jìn)行的操作        {//獲取解析后HTML的大小System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle;int width = rectangle.Width;int height = rectangle.Height;//設(shè)置解析后HTML的可視區(qū)域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));//設(shè)置圖片文件保存路徑和圖片格式,格式可以自定義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

然后把圖片轉(zhuǎn)換為PDF,這里需要用到 iTextSharp.dll 這個(gè)組件。


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();//是否顯式滾動(dòng)條webBrowser.ScrollBarsEnabled = false;//加載 htmlwebBrowser.DocumentText = html;            //頁(yè)面加載完成執(zhí)行事件webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
        }private void webBrowser_DocumentCompleted(object sender, EventArgs e)//這個(gè)就是當(dāng)網(wǎng)頁(yè)載入完畢后要進(jìn)行的操作        {//獲取解析后HTML的大小System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle;int width = rectangle.Width;int height = rectangle.Height;//設(shè)置解析后HTML的可視區(qū)域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));//設(shè)置圖片文件保存路徑和圖片格式,格式可以自定義string filePath = AppDomain.CurrentDomain.BaseDirectory + "../../SaveFIle/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
            bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);//創(chuàng)建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);       // 添加圖片對(duì)像                doc.Close();return ms.ToArray();
            }
        }
    }
View Code

不過(guò)這種生成圖片之后再轉(zhuǎn)成PDF,會(huì)造成像素的丟失,所以看起來(lái)要比圖片模糊一點(diǎn)。

還有一種辦法就是直接生成PDF,這里需要安裝 ABCpdf。不過(guò),這個(gè)是收費(fèi)的。。。


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>";//創(chuàng)建一個(gè)Doc對(duì)象Doc doc = new Doc();//Rect默認(rèn)是文檔整個(gè)頁(yè)面大小,這里的Inset表示將Rect左右留出15的空白,上下留出20的空白doc.Rect.Inset(15, 20);//直接設(shè)置htmlint docID = doc.AddHtml(html);//設(shè)置URL//int docID = doc.AddImageUrl("");//設(shè)置字體doc.AddFont("Arial");while (true)
            {//判斷是否還有內(nèi)容if (!doc.Chainable(docID))
                {break;
                }//如果還有內(nèi)容就添加一頁(yè)doc.Page = doc.AddPage();//根據(jù)ID添加內(nèi)容并返回頁(yè)面上該內(nèi)容對(duì)應(yīng)的新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

看完了這篇文章,相信你對(duì)C#將HTML轉(zhuǎn)換為圖片或PDF的方法有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

新聞名稱:C#將HTML轉(zhuǎn)換為圖片或PDF的方法
文章URL:http://muchs.cn/article2/ijsoic.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站、品牌網(wǎng)站設(shè)計(jì)、域名注冊(cè)、小程序開(kāi)發(fā)、自適應(yīng)網(wǎng)站企業(yè)網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)