How to save a system.drawing.graphics object to a PDF file using PDFsharp?

4.3k Views Asked by At

I have searched for hours trying to find out how to do this without any success.

I did find the 'FromGraphics' command which reads a 'system.drawing.graphics' object into the XGraphics type, but am unsure how to add this to the PDF output.

Most examples I find show how to take images from an existing file and save them to a PDF, but how do I do this with a pre-made system.drawing.graphics object that has been made pragmatically?

A C# and/or VB.net example would be very much appreciated instead of a GIF.

E.g. how do I change an example like the following to use the system.drawing.graphics object?

string pdfpath = Server.MapPath("PDFs");
string imagepath = Server.MapPath("Images");
Document doc = new Document();
try
{
  PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf",   FileMode.Create));
  doc.Open();

  doc.Add(new Paragraph("GIF"));
  Image gif = Image.GetInstance(imagepath + "/mikesdotnetting.gif");
  doc.Add(gif);
}
catch (Exception ex)
{
  //Log error;
}
finally
{
  doc.Close();
}
2

There are 2 best solutions below

5
On

Short example:

Dim pdfDoc As New PdfDocument
Dim page As New PdfPage
pdfDoc.Pages.Add(page)
Dim xg = XGraphics.FromPdfPage(page)
 'use the xg object to draw on the pdf page
pdfDoc.Save("path to file")
0
On

To answer the main question "How to save a system.drawing.graphics object to a PDF file using PDFsharp?"
You can't do that. You can use the XGraphics class to draw on PDF pages, on the screen, on a printer. You can create an XGraphics object for a PDF page or from a Graphics object. But anything that was drawn on the Graphics object with other than XGraphics routines will not appear in the PDF.

The other question: "How do I change an example like the following to use the system.drawing.graphics object?"
You need an XGraphics object to draw on PDF. User OneFineDay showed how to get one. Then you use xg.DrawImage(...) to draw images on a PDF page. You do not need a Graphics object unless you also want to draw on other media than PDF pages.