6

Completely unable to render JPEG image to PDF using PdfSharpCore.

Code is as simple as

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

I know that ImageSource.ImageSourceImpl has to be set, and I've set it to the simplest ImageSharp-based implementation: ImageSource.ImageSourceImpl = new ImageSharpImageSource() which is indeed valid because XImage is being saved as logo1.jpg properly.

But my PDF is visually blank. Binary content is there, and it seem that all format properties are OK, but binary data is somewhat different from the source.

Here is how my ImageSharp implementation saves/loads the image:

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

Finally, PDF piece:

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

Please help, I'm stuck for a few days! New to this stuff so probably missing something?..

NOTE: gfx.DrawString() methods work properly, so I'm able to render text with the same setup.

4

1 回答 1

0

请使用此方法:-

    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 然后删除该图像,请参考以下内容:-更多链接

于 2018-06-28T08:49:16.077 回答