How does C # convert HTML to a picture or PDF?

Source: Internet
Author: User
Tags ming
The first is to convert HTML to images.
public partial class Form1: Form
    {public Form1 ()
        {
            InitializeComponent ();
        }

        WebBrowser webBrowser = null; public void ConvertToImg ()
        {
            webBrowser = new WebBrowser (); // Whether an explicit scroll bar webBrowser.ScrollBarsEnabled = false; // The address of the loading HTML page webBrowser.Navigate (""); // The page load completion execution event webBrowser.DocumentCompleted + = new WebBrowserDocumentCompletedEventHandler ( webBrowser_DocumentCompleted);
        } private void webBrowser_DocumentCompleted (object sender, EventArgs e) // This is the operation to be performed after the web page is loaded. {// Get the size of the parsed HTML System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle; int width = rectangle.Width; int height = rectangle.Height; // Set the visible area of the HTML after parsing 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)); // Set the image file save path and image format, the format can be customized 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
The above method is to parse the HTML of the specified URL and then convert it to an image. Of course, you can also write some HTML tags directly. as follows:

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; \"> Field 1 </ th> <th style = \ "width: 60px; \"> Field 2 </ th> <th style = \ "width: 60px; \"> Field 3 </ th> </ tr> <tr style = \ "color: green; \"> <td> Xiao Ming </ 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 (); // Whether to explicitly scroll the webBrowser.ScrollBarsEnabled = false; // Load htmlwebBrowser.DocumentText = html; // The page load completion execution event webBrowser.DocumentCompleted + = new WebBrowserDocumentCompletedEventHandler (webBrowser_DocumentCompleted);
        } private void webBrowser_DocumentCompleted (object sender, EventArgs e) // This is the operation to be performed after the web page is loaded. {// Get the size of the parsed HTML System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle; int width = rectangle.Width; int height = rectangle.Height; // Set the visible area of the HTML after parsing 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)); // Set the image file save path and image format, the format can be customized 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
Then convert the image to PDF, iTextSharp.dll is needed here.

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; \"> Field 1 </ th> <th style = \ "width: 60px; \"> Field 2 </ th> <th style = \ "width: 60px; \"> Field 3 </ th> </ tr> <tr style = \ "color: green; \"> <td> Xiao Ming </ 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 (); // Whether to explicitly scroll the webBrowser.ScrollBarsEnabled = false; // Load htmlwebBrowser.DocumentText = html; // The page load completion execution event webBrowser.DocumentCompleted + = new WebBrowserDocumentCompletedEventHandler (webBrowser_DocumentCompleted);
        } private void webBrowser_DocumentCompleted (object sender, EventArgs e) // This is the operation to be performed after the web page is loaded. {// Get the size of the parsed HTML System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle; int width = rectangle.Width; int height = rectangle.Height; // Set the visible area of the HTML after parsing 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)); // Set the image file save path and image format, the format can be customized string filePath = AppDomain.CurrentDomain.BaseDirectory + ".. /../SaveFIle/ "+ DateTime.Now.ToString (" yyyyMMddHHmmssfff ") +" .png ";
            bitmap.Save (filePath, System.Drawing.Imaging.ImageFormat.Png); // Create 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); // left and right 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); // scaling ratio doc.Add (img); // add image object doc.Close (); return ms.ToArray ();
            }
        }
    }
View Code
However, this kind of generated image and then converted to PDF will cause the loss of pixels, so it looks a bit blurier than the image.

Another way is to generate PDF directly, ABCpdf needs to be installed here. However, this is charged. . .

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; \"> Field 1 </ th> <th style = \ "width: 60px; \"> Field 2 </ th> <th style = \ "width: 60px; \"> Field 3 </ th> </ tr> <tr style = \ "color: green; \"> <td> Xiao Ming </ td> <td> 22 </ td> <td> 185 </ td> </ tr> < tr style = \ "color: red; \"> <td> 小青 </ td> <td> 21 </ td> <td> 170 </ td> </ tr> </ table> </ div> " ; // Create a Doc object Doc doc = new Doc (); // Rect defaults to the entire page size of the document. Here Inset means leave Rect with 15 spaces left and right, and leave 20 spaces up and down. 15, 20); // directly set htmlint docID = doc.AddHtml (html); // set URL // int docID = doc.AddImageUrl (""); // set font doc.AddFont ("Arial"); while (true)
            {// Judge if there is still content if (! Doc.Chainable (docID))
                {break;
                } // If there is content, add a page doc.Page = doc.AddPage (); // Add content based on the ID and return the new ID corresponding to the content on the page 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 ();
        }
        
    }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.