如何保存包含GridView和Charts的div截图或转为PDF、JPG文件?
Hey there! I’ve been in your shoes before—trying to capture GridView and Chart controls with iTextSharp only to hit a wall because it doesn’t handle those complex web elements well. Let me share a couple of proven solutions that should get you what you need:
This library does a way better job rendering HTML with complex controls like GridView and Charts compared to iTextSharp. It can generate both PDF and image files directly from the HTML of your target div.
Steps to implement:
- Install the
HtmlRenderer.PdfSharpNuGet package in your project. - Capture the full HTML content of your div control.
- Use the library to render that HTML into PDF or JPG.
Code Example:
// Capture the HTML of your target div StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter); yourTargetDiv.RenderControl(htmlWriter); string divHtml = stringWriter.ToString(); // Generate PDF PdfDocument pdfDocument = PdfGenerator.GeneratePdf(divHtml, PageSize.A4); pdfDocument.Save(@"C:\YourPath\output.pdf"); // Generate JPG Bitmap divBitmap = PdfGenerator.GenerateImage(divHtml, PageSize.A4.Width, PageSize.A4.Height); divBitmap.Save(@"C:\YourPath\output.jpg", ImageFormat.Jpeg);
If you need pixel-perfect captures (especially for Charts that rely on JavaScript to render), using Selenium to simulate a browser is the way to go. It renders the page exactly like a real Chrome browser, so all styles and dynamic content will be captured correctly.
Steps to implement:
- Install the
Selenium.WebDriverandSelenium.WebDriver.ChromeDriverNuGet packages. - Set up a headless Chrome instance to load your page.
- Locate the target div and capture its screenshot, or print the page to PDF.
Code Example:
// Configure Chrome options for headless mode ChromeOptions options = new ChromeOptions(); options.AddArgument("--headless=new"); // Modern headless mode options.AddArgument("--disable-gpu"); options.AddArgument("--no-sandbox"); using (ChromeDriver driver = new ChromeDriver(options)) { // Navigate to your page driver.Navigate().GoToUrl("https://your-app-url/your-page"); // Wait for dynamic content (like Charts) to load - use WebDriverWait for reliability WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); wait.Until(d => d.FindElement(By.Id("your-target-div-id"))); // Capture div screenshot as JPG IWebElement divElement = driver.FindElement(By.Id("your-target-div-id")); Screenshot divScreenshot = divElement.GetScreenshot(); divScreenshot.SaveAsFile(@"C:\YourPath\div-screenshot.jpg", ScreenshotImageFormat.Jpeg); // Save page as PDF (includes the div and surrounding content) var printParams = new Dictionary<string, object> { {"printBackground", true}, {"paperWidth", 8.5}, {"paperHeight", 11} }; var pdfResult = driver.ExecuteChromeCommand("Page.printToPDF", printParams); byte[] pdfBytes = Convert.FromBase64String(pdfResult["data"].ToString()); File.WriteAllBytes(@"C:\YourPath\page-output.pdf", pdfBytes); }
If you’re running on a Windows server, you can use the built-in WebBrowser control to render the HTML and capture it as a bitmap. This is a more lightweight option but only works in Windows environments.
Code Example:
using System.Windows.Forms; // Add reference to System.Windows.Forms WebBrowser browser = new WebBrowser(); browser.ScrollBarsEnabled = false; browser.DocumentText = divHtml; // Use the same div HTML from Solution 1 // Wait for the document to fully render while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } // Set browser size to match the div browser.Width = yourTargetDiv.Width; browser.Height = yourTargetDiv.Height; // Capture to bitmap Bitmap bitmap = new Bitmap(browser.Width, browser.Height); browser.DrawToBitmap(bitmap, new Rectangle(0, 0, browser.Width, browser.Height)); bitmap.Save(@"C:\YourPath\output.jpg", ImageFormat.Jpeg);
Why iTextSharp Failed
iTextSharp is great for basic PDF generation, but it doesn’t handle dynamic JavaScript rendering or complex CSS styling well. GridView controls rely on CSS for layout, and many Chart controls use JavaScript to draw visuals—iTextSharp can’t interpret or render those, hence the failure. The solutions above either use better HTML rendering engines or browser simulation to overcome this.
内容的提问来源于stack exchange,提问作者satya prakash sharma

