empira / PDFsharp-1.5

A .NET library for processing PDF
MIT License
1.28k stars 587 forks source link

NullReferenceException XGraphics.DrawImage() when XImage Pixel format is Format1bppIndexed #27

Closed neil445 closed 6 years ago

neil445 commented 7 years ago

I am trying to put QRCode on a PDF file. Here's my code:

        PdfDocument document = new PdfDocument();
        PdfPage page = document.AddPage();
        page.Orientation = PdfSharp.PageOrientation.Portrait;
        page.Width = XUnit.FromInch(8.5);
        page.Height = XUnit.FromInch(11);
        XGraphics gfx = XGraphics.FromPdfPage(page);
        XImage xImage = XImage.FromGdiPlusImage(image);
        gfx.DrawImage(xImage, 10, 10, 290, 290);
        document.Save("test.pdf");

I'm getting a null reference exception, here's the stacktrace: at PdfSharp.Pdf.Advanced.PdfImage.ReadIndexedMemoryBitmap(Int32 bits) at PdfSharp.Pdf.Advanced.PdfImage..ctor(PdfDocument document, XImage image) at PdfSharp.Pdf.Advanced.PdfImageTable.GetImage(XImage image) at PdfSharp.Pdf.PdfPage.GetImageName(XImage image) at PdfSharp.Drawing.Pdf.XGraphicsPdfRenderer.Realize(XImage image) at PdfSharp.Drawing.Pdf.XGraphicsPdfRenderer.DrawImage(XImage image, Double x, Double y, Double width, Double height) at PdfSharp.Drawing.XGraphics.DrawImage(XImage image, Double x, Double y, Double width, Double height) at UniWallet.Services.ApiApplication.Extensions.ImageExtensions.ToPDFFileByteArray(Image image) in C:\CODES\UniWallet\UniWallet_Dev\UniWallet.Services\Api\UniWallet.Services.ApiApplication\Extensions\ImageExtensions.cs:line 48 at UniWallet.Services.ApiApplication.Test.Extensions.ImageExtensionsTest.Create() in C:\CODES\UniWallet\UniWallet_Dev\UniWallet.Services\Api\UniWallet.Services.ApiApplication.Test\Extensions\ImageExtensionsTest.cs:line 36

I tried to follow the stack trace, and here's where I ended up: PDFImage.cs case PixelFormat.Format1bppIndexed: ReadIndexedMemoryBitmap(1/*, ref hasMask*/); break;

I tried images with other pixel format, meaning pictures with some color, and the code worked. Looks like there's something happening when an image with only two colors (black and white) is being used.

THANKS.

ThomasHoevel commented 7 years ago

Please give us a complete VS solution that allows us to replicate the issue. See also: http://www.pdfsharp.net/wiki/IssueSubmissions.ashx Thanks.

TH-Soft commented 6 years ago

I created a monochrome bitmap and the code snippet from above worked flawless with RC1. Cannot replicate the issue.

SteffPeff commented 5 years ago

I have the same issue, but it doesn't occur in the first PDF you create, but in the second. Probably because _gfx is set to null after closing and not reinitialized correctly when opening / creating the second one.