I'm trying to add a picture of part of a form to a PDF so I'm using PDFsharp, but one of the problems I have is that I can't delete the picture after I have added it to the PDF file.
This is the code I'm using:
private void button12_Click(object sender, EventArgs e)
{
string path = @"c:\\Temp.jpeg";
Bitmap bmp = new Bitmap(314, this.Height);
this.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
bmp.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
GeneratePDF("test.pdf",path);
var filestream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
if (File.Exists(path))
{
File.Delete(path);
}
}
private void GeneratePDF(string filename, string imageLoc)
{
PdfDocument document = new PdfDocument();
// Create an empty page or load existing
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
DrawImage(gfx, imageLoc, 50, 50, 250, 250);
// Save and start View
document.Save(filename);
Process.Start(filename);
}
void DrawImage(XGraphics gfx, string jpegSamplePath, int x, int y, int width, int height)
{
XImage image = XImage.FromFile(jpegSamplePath);
gfx.DrawImage(image, x, y, width, height);
}
The FileStream
is there because I was trying to make sure that it was closed and if that was the problem.
This is where I got the code for writing the picture to the PDF overlay-image-onto-pdf-using-pdfsharp and this is where I got the code to make a picture of the form capture-a-form-to-image
Did I miss something obvious?
Or is there a better way to do this?
If you read the details of the System.IO.IOException
it tells you that
the file cannot be accessed because it is used by another process.
The process that is still using your image is this nice object:
XImage image = XImage.FromFile(jpegSamplePath);
The solution would be to dispose the image after you have drawn it to the PDF:
void DrawImage(XGraphics gfx, string jpegSamplePath, int x, int y, int width, int height)
{
XImage image = XImage.FromFile(jpegSamplePath);
gfx.DrawImage(image, x, y, width, height);
image.Dispose();
}
And now the Exception vanishes into thin air....as does your file...
EDIT
A more elegant solution would be use a using
block, this will make sure that Dispose()
is called after you are finished with the file:
void DrawImage(XGraphics gfx, string jpegSamplePath, int x, int y, int width, int height)
{
using (XImage image = XImage.FromFile(jpegSamplePath))
{
gfx.DrawImage(image, x, y, width, height);
}
}