如何将图像保存为图像/ pdf?
问题描述:
HI全部, 我确实有一个胜利的形式,它像一个售票机。 我有一个页面,我将获得所有的用户信息,然后点击一个名为Generate Bill的按钮,将会显示一个带有标签控件的ht背景(如公司徽标名称等)来自以前表单的信息。如何保存新表单(票证)?如何将图像保存为图像/ pdf?
我该怎么做?
答
我的CC.Utilities增加了一个DrawToImage()
扩展方法到Control
类可能会帮助你。我会在一秒内发布一些代码片段。
辅助方法:
/// <summary>
/// Captures an <see cref="Image"/> of the specified window
/// </summary>
/// <param name="handle">The handle of the window to capture</param>
/// <returns>An <see cref="Image"/> of the specified window</returns>
public static Image CaptureWindow(IntPtr handle)
{
IntPtr hdcSrc = User32.GetWindowDC(handle);
RECT windowRect = new RECT();
User32.GetWindowRect(handle, windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
IntPtr hdcDest = Gdi32.CreateCompatibleDC(hdcSrc);
IntPtr hBitmap = Gdi32.CreateCompatibleBitmap(hdcSrc, width, height);
IntPtr hOld = Gdi32.SelectObject(hdcDest, hBitmap);
Gdi32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, InteropConstants.SRCCOPY);
Gdi32.SelectObject(hdcDest, hOld);
Gdi32.DeleteDC(hdcDest);
User32.ReleaseDC(handle, hdcSrc);
Image image = Image.FromHbitmap(hBitmap);
Gdi32.DeleteObject(hBitmap);
return image;
}
的P /调用:
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetWindowRect(IntPtr hWnd, [Out] RECT rect);
[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)]
public class RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
扩展方法:
/// <summary>
/// Draws the <see cref="Control"/> to an <see cref="Image"/>
/// </summary>
/// <param name="control">The <see cref="Control"/> to draw.</param>
/// <returns>An <see cref="Image"/> of the <see cref="Control"/></returns>
public static Image DrawToImage(this Control control)
{
return Utilities.CaptureWindow(control.Handle);
}
的命名空间是一点点从复制/粘贴搞砸但是如果您需要更多的东西,您可以查看完整的项目,或者这可能足以让您指向正确的方向。
谢谢Cory, 会尝试,并回到你的... – nimi 2010-02-08 06:57:10
听起来不错。请注意,'Control'有一个'DrawToBitmap()'方法,可能也适用于你。我写了这个方法被破坏的情况,比如在一个'WebBrowser'控件上,它总是从'DrawToBitmap()' – 2010-02-08 07:01:36
+1好答案返回一个纯白色图像。如果需要的话,可以使用iTextSharp或类似的工具将图像添加到PDF文档中。 – 2010-02-08 13:18:44