【发布时间】:2018-06-21 05:39:02
【问题描述】:
完全无法使用 PdfSharpCore 将 JPEG 图像呈现为 PDF。
代码就这么简单
public byte[] GetPdfContent()
{
ImageSource.ImageSourceImpl = new ImageSharpImageSource();
var document = new PdfDocument();
var logo = XImage.FromFile("logo.jpg");
// this is test line, I'm saving XImage result and it is identical to the source file!
File.WriteAllBytes("logo1.jpg", logo.AsJpeg().ToArray());
var page = document.AddPage();
var gfx = XGraphics.FromPdfPage(page);
gfx.DrawImage(logo, 0, 0);
using (var stream = new MemoryStream())
{
document.Save(stream, false);
return stream.ToArray();
}
}
我知道必须设置ImageSource.ImageSourceImpl,并且我已将其设置为基于ImageSharp 的最简单实现:ImageSource.ImageSourceImpl = new ImageSharpImageSource() 这确实有效,因为XImage 被正确保存为logo1.jpg。
但我的 PDF 在视觉上是空白的。二进制的内容是有的,好像所有的格式属性都OK,但是二进制数据和源有点不一样。
这是我的 ImageSharp 实现如何保存/加载图像:
public class ImageSharpImageSource : ImageSource
{
protected override IImageSource FromFileImpl(string path, int? quality = 75)
{
return new ImageSharpImageSourceImpl(path, () =>
{
return Image.Load<Rgb24>(path, new JpegDecoder());
}, (int)quality);
}
private class ImageSharpImageSourceImpl : IImageSource
{
public void SaveAsJpeg(MemoryStream ms)
{
Image.SaveAsJpeg(ms, new JpegEncoder());
}
}
}
最后,PDF 篇:
7 0 obj % PdfSharpCore.Pdf.Advanced.PdfImage
<<
/BitsPerComponent 8
/ColorSpace /DeviceRGB
/Filter /DCTDecode
/Height 340
/Interpolate true
/Length 16443
/Subtype /Image
/Type /XObject
/Width 340
>>
stream <<BINARY DATA>>
请帮忙,我被困了几天!刚接触这些东西,所以可能遗漏了什么?..
注意:gfx.DrawString() 方法可以正常工作,因此我可以使用相同的设置呈现文本。
【问题讨论】:
-
注意:这个问题不是关于原始 PDFsharp 版本,而是关于 PDFsharp 的一个端口。
-
@Ballyoleidjit 标题中提到了,但是没有PdfSharpCore的标签
-
@IvanZverev 你有没有在 PdfSharpCore 中解决这个问题?
-
@PeterReay 不幸的是,没有
标签: c# pdfsharp imagesharp