c# - PdfSharpCore 图像渲染问题

标签 c# pdfsharp imagesharp

完全无法使用 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() 方法可以正常工作,因此我能够使用相同的设置呈现文本。

最佳答案

请使用这个方法:-

    internal void SaveImageAsPdf(string imageFileName, string pdfFileName, int width = 600)
    {
        using (var document = new PdfDocument())
        {
            PdfPage page = document.AddPage();
            using (XImage image = XImage.FromFile(imageFileName))
            {
                var height = (int)(((double)width / (double)image.PixelWidth) * image.PixelHeight);

                page.Width = width;
                page.Height = height;

                XGraphics graphics = XGraphics.FromPdfPage(page);
                graphics.DrawImage(image, 0, 0, width, height);                
            }
            document.Save(pdfFileName);
        }
    }

如果您需要更多引用,例如我们将图像转换为 pdf 然后删除该图像,请引用:- Link更多

关于c# - PdfSharpCore 图像渲染问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50961076/

相关文章:

c# - SharpSVN - 服务器证书验证失败

C# 从 web 服务下载文件

c# - wpf:嵌套菜单项的绑定(bind)

c# - 如何使用 ImageSharp 创建 Gif .net Core2

c# - 如何合并两张图片?

c# - 无法使用 mdbg 从进程分离

c# - 通过列表循环 foreach,为不同的值执行代码

pdfsharp - 将多页 MigraDoc 文档添加到 PDFSharp 文档

c# - 如何使用 PdfSharp 将 .SVG 写入 pdf

c# - ImageSharp.Web 与 AzureBlobStorageImageProvider 给出 404