【发布时间】:2017-12-06 11:07:21
【问题描述】:
我想使用 PDFsharp 和 MigraDoc 来生成 PDF。就目前而言,一切正常。
现在我想出了一个想法,即在运行时创建位图并将其添加到我的一个表格单元格中。
我了解到可以从资源中添加位图,因此无需将它们放在硬盘驱动器上。
见:http://www.pdfsharp.net/wiki/MigraDoc_FilelessImages.ashx
这是我尝试使其适应我的小项目:
创建位图的代码:
Bitmap GreenDot = new Bitmap(32,32);
Graphics GreenDotGraphics = Graphics.FromImage(GreenDot);
GreenDotGraphics.FillEllipse(Brushes.Green,0,0,32,32);
//The next step will be converting the Bitmap to an byte[]
var byteGreenDot = ImageToByte(GreenDot);
//Now converting it to string as seen in the WikiPage
string stringGreenDot = Convert.ToBase64String(byteGreenDot);
string FinalGreenDot = "base64:"+ stringGreenDot;
//Now creating a table
.
.
.
cell = MyRow.Cell[1];
cell.AddImage(FinalGreenDot);
.
.
.
位图转字节[]代码
public static byte[] ImageToByte(System.Drawing.Image img)
{
using(var ms = new MemoryStream())
{
img.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp);
return ms.ToArray();
}
}
当我运行代码时,我会收到一条警告说“警告:找不到图像 'base64:Qk02E[...]=='。” (这篇文章的 base64 字符串被截断了)。
我猜我没有正确地将它转换为字节[]。
谁能让我走上正轨?
【问题讨论】:
-
AddImage()的第一个参数的数据类型不是定义为string吗?这将解释错误消息,因为图像对象通过ToString()隐式转换为字符串。在这种情况下,您需要声明文件名而不是流(至少在我的项目中我需要传递文件名)。 -
请阅读链接的 Wiki 文章。
-
是的,文章说了什么?
section.AddImage(imageFilename);- 你在变量名中看到Filename这个词了吗?这就是为什么我写你需要传递一个文件名。 -
MigraDoc 现在接受包含带有前缀“base64:”的 BASE64 编码图像的文件名。在这种情况下,文件名不引用文件,文件名包含位图的所有位,采用 BASE64 编码的 ASCII 字符串。字节数组(C# 中的 byte[])可以轻松转换为文件名。如果您有一个流,您可以轻松地将其读入字节数组并使用它。不过,感谢您的努力。
-
BASE64 编码已正确完成,但原始消息中显示的警告以一种误导的方式被截断,将“BYTES”而不是实际的 BASE64 数据,因此给人一种错误的印象(至少我)。
标签: c# bitmap pdfsharp migradoc