FJPoort
FJPoort

Reputation: 245

How to convert Windows Form to PDF including values of textboxes

I have created a Windows Application in Visual Studio 2005. In this application, the user is able to export the current active form to a PDF file.

The problem is how do I save it with the values of textboxes? When I leave them empty, there's no problem. Then I give some input and get output in textboxes, I click export, and I get a message "A generic error occurred in GDI+". And in Output window of Visual Studio:

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
A first chance exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll

Here's my code:

For capturing active screen:

try
{
    Rectangle bounds = this.Bounds;
    using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
    {
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
        }
        bitmap.Save("C://Rectangle.bmp", ImageFormat.Bmp);
    }
}
catch(Exception e)
{
    MessageBox.Show(e.Message.ToString());
}

For exporting to pdf:

captureScreen();

PdfDocument doc = new PdfDocument();

PdfPage oPage = new PdfPage();

doc.Pages.Add(oPage);
oPage.Rotate = 90;
XGraphics xgr = XGraphics.FromPdfPage(oPage);
XImage img = XImage.FromFile(@"C://Rectangle.bmp");

xgr.DrawImage(img, 0, 0);

doc.Save("C://RectangleDocument.pdf");
doc.Close();

Please help me on exporting the form to pdf including values of textboxes.

Upvotes: 1

Views: 4607

Answers (1)

Tim Copenhaver
Tim Copenhaver

Reputation: 3302

I am assuming this exception is thrown when you try to call CopyFromScreen? I have written very similar code before with no problems, but there are a few minor differences.

The first thing I see is that the Bounds property returns a point as a relative position, but the CopyFromScreen method expects the point as an absolute position. You probably want to call this.PointToScreen to get the absolute screen position of the point before calling CopyFromScreen.

Second, it should "just work" but just for my own sanity I usually use CopyPixelOption.SourceCopy in the CopyFromScreen call.

I'm not sure about the implementation of CopyFromScreen and Bitmap.Save, but you might want to move the Save call so it happens before the graphics object is disposed. This is probably not necessary, but if there's any sort of delayed computation going on that could cause you problems.

Upvotes: 1

Related Questions