public void ToByteArray_CorrectFrame() { Bill bill = SampleData.CreateExample4(); bill.Format.OutputSize = OutputSize.A4PortraitSheet; using MetafileCanvas canvas = new MetafileCanvas(QRBill.A4PortraitWidth, QRBill.A4PortraitHeight, "Helvetica, Arial, \"Liberation Sans\""); QRBill.Draw(bill, canvas); EmfMetaInfo metaInfo = new EmfMetaInfo(canvas.ToByteArray()); Assert.Equal(257, metaInfo.NumRecords); var scale = metaInfo.Dpi / 25.4f; // Returns the frame in pixels var frame = metaInfo.GetFrame(); Assert.Equal(0, frame.Left); Assert.Equal(0, frame.Top); int expectedWidth = (int)(QRBill.A4PortraitWidth * scale); Assert.InRange(frame.Right, expectedWidth - 2, expectedWidth + 2); int expectedHeight = (int)(QRBill.A4PortraitHeight * scale); Assert.InRange(frame.Bottom, expectedHeight - 2, expectedHeight + 2); }
private static ConversionResult Convert(Stream stream, IReadOnlyDictionary <string, object> context) { // copy metafile to buffer using MemoryStream buffer = new MemoryStream(); stream.CopyTo(buffer); // retrieve DPI from metafile EmfMetaInfo metaInfo = new EmfMetaInfo(buffer.ToArray()); int sourceDpi = metaInfo.Dpi; // read metafile buffer.Position = 0; using Metafile metafile = (Metafile)Image.FromStream(buffer); // compute bitmap size (300 dpi, independent of source DPI) var pageUnit = GraphicsUnit.Pixel; var metafileBounds = metafile.GetBounds(ref pageUnit); float scale = 300f / sourceDpi; var bitmapRect = new Rectangle(0, 0, (int)Math.Round(metafileBounds.Width * scale), (int)Math.Round(metafileBounds.Height * scale)); // create bitmap and fill with white background using Bitmap bitmap = new Bitmap(bitmapRect.Width, bitmapRect.Height, PixelFormat.Format24bppRgb); bitmap.SetResolution(300, 300); using Graphics graphics = Graphics.FromImage(bitmap); graphics.FillRectangle(Brushes.White, bitmapRect); // draw metafile to bitmap graphics.DrawImage(metafile, bitmapRect, metafileBounds, pageUnit); // save bitmap as PNG MemoryStream result = new MemoryStream(); bitmap.Save(result, ImageFormat.Png); // return PNG return(new ConversionResult(null, "png", result)); }