using System.Windows.Forms; using iTextSharp.text.pdf; using iTextSharp.text; namespace ActiveTest { public partial class Test : Page { protected void CreatePDF(object sender, EventArgs e) { string fileName = "PrintView"; Document doc = new Document(); string f = Server.MapPath(string.Format("~/Temp/{0}.pdf",fileName)); PdfWriter.GetInstance(doc, new FileStream(f, FileMode.Create)); doc.Open(); /// /// A4 Size /// int width = 585; int height = 842; string url = this.Request.Url.ToString() + "?m=Print"; Image thumbnail = new Image(url, width, height, width, height, Image.ImageMethod.Url); Bitmap image = thumbnail.GenerateImage(); string p = Server.MapPath(string.Format("~/Temp/{0}.bmp",fileName)); image.Save(p); iTextSharp.text.Image i = iTextSharp.text.Image.GetInstance(p); doc.Add(i); doc.Close(); File.Delete(p); /// /// use pdf file /// File.Delete(f); } } public class Image { public enum ImageMethod { Url, Html }; public string Url { get; set; } public Bitmap Current { get; set; } public int Width { get; set; } public int Height { get; set; } public int BrowserWidth { get; set; } public int BrowserHeight { get; set; } public string Html { get; set; } public ImageMethod Method { get; set; } public Image(string data, int browserWidth, int browserHeight, int width, int height, ImageMethod method) { this.Method = method; if (method == ImageMethod.Url) this.Url = data; else if (method == ImageMethod.Html) this.Html = data; this.BrowserWidth = browserWidth; this.BrowserHeight = browserHeight; this.Height = height; this.Width = width; } public Bitmap GenerateImage() { Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); return Current; } private void GenerateThumbnailInteral() { WebBrowser webBrowser = new WebBrowser(); webBrowser.ScrollBarsEnabled = false; if (this.Method == ImageMethod.Url) webBrowser.Navigate(this.Url); else webBrowser.DocumentText = this.Html; webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted); while (webBrowser.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents(); webBrowser.Dispose(); } private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser webBrowser = (WebBrowser)sender; webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight); webBrowser.ScrollBarsEnabled = false; this.Current = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height); webBrowser.BringToFront(); webBrowser.DrawToBitmap(Current, webBrowser.Bounds); this.Current = (Bitmap)Current.GetThumbnailImage(Width, Height, null, IntPtr.Zero); } } }
References:
No comments:
Post a Comment