【问题标题】:How to save a system.drawing.graphics object to a PDF file using PDFsharp?如何使用 PDFsharp 将 system.drawing.graphics 对象保存到 PDF 文件?
【发布时间】:2015-06-04 22:38:53
【问题描述】:

我已经搜索了几个小时试图找出如何做到这一点,但没有任何成功。

我确实找到了将“system.drawing.graphics”对象读入 XGraphics 类型的“FromGraphics”命令,但不确定如何将其添加到 PDF 输出中。

我发现的大多数示例都展示了如何从现有文件中获取图像并将其保存为 PDF,但是如何使用已实用的预制 system.drawing.graphics 对象来执行此操作?

非常感谢 C# 和/或 VB.net 示例而不是 GIF。

例如如何更改如下示例以使用 system.drawing.graphics 对象?

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();
}

【问题讨论】:

  • 你得到了很好的答案。只是为了确保您做对了:Graphics 对象不包含任何图形。它只是在 a) 表面 b) 位图 c) 打印页面上绘制像素的工具。或者 d) 转换成 PDF,如果您使用 pdf 库中的特殊 Graphics 对象..

标签: c# vb.net pdf pdfsharp system.drawing.graphics


【解决方案1】:

简短示例:

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")

【讨论】:

  • 抱歉,我没听懂。如果我有一个预先制作的 system.drawing.graphics 对象存储到图形中,我将它移动到 XGraphics gfx 对象:例如。 XGraphics gfx = FromGraphics(graphics, size) 如何将 gfx 对象添加到 PDF 文件页面?我是否使用图像类型,如果使用,如何使用?
  • 调用xg 对象的方法。即xg.DrawString(...)
  • 我自己使用XGraphics.FromPdfPage。它直接绘制到页面。
  • FromGraphics(graphics, size) 将在具有图形的控件上绘制(如图片框) - 请参阅docs,因此此方法不会绘制到 pdf 页面
  • Graphics 对象不存储任何内容,GraphicsPath 可以。
【解决方案2】:

回答主要问题“如何使用 PDFsharp 将 system.drawing.graphics 对象保存到 PDF 文件?”
你不能那样做。您可以使用 XGraphics 类在 PDF 页面、屏幕、打印机上绘图。您可以为 PDF 页面或从 Graphics 对象创建 XGraphics 对象。但是,使用 XGraphics 例程以外的方法在 Graphics 对象上绘制的任何内容都不会出现在 PDF 中。

另一个问题:“如何更改如下示例以使用 system.drawing.graphics 对象?”
您需要一个 XGraphics 对象才能在 PDF 上绘图。用户 OneFineDay 展示了如何获得一个。然后使用xg.DrawImage(...) 在 PDF 页面上绘制图像。除非您还想在 PDF 页面以外的其他媒体上绘图,否则您不需要 Graphics 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2019-04-09
    相关资源
    最近更新 更多