开发者

Printing images with partial transparency without introducing distortions

开发者 https://www.devze.com 2023-02-16 01:41 出处:网络
I\'m having some troubles printing images and texts that have a 8 bit alpha channel. It looks like most printer drivers will incorrectly render the alpha channel, adding some dithering patterns instea

I'm having some troubles printing images and texts that have a 8 bit alpha channel.

It looks like most printer drivers will incorrectly render the alpha channel, adding some dithering patterns instead of blending the various layers.

For instance, the code at the end of this question produces something like this (notice the dithering in the left square): Virtual PDF printer - Laser printer

So far only the XPS virtual printer works fine.

What I've always done to avoid this is printing on an intermediate bitmap, but for a standard 11x8.5'' page at 1200 DPI it would take approx 400 MB of RAM just for storing this bitmap and I'm now wondering which is the correct way to print such objects.

Thanks

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        PrintDocument printDoc = new PrintDocument();
        printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);

        PrintDialog print = new PrintDialog();
        print.Document = printDoc;
        if (print.ShowDialog() == DialogResult.OK)
            printDoc.Print();
    }

    static void printDoc_PrintPage(object sender, PrintPageEventArgs e)
    {
        //draw directly on the print graphics
        e.Graphics.TranslateTransform(50, 50);
        drawStuff(e.Graphics);

        //draw on an intermediate bitmap
        e.Graphics.ResetTransform();
        using (Bitmap bmp = new Bitmap((int)e.Graphics.DpiX, (int)e.Graphics.DpiY))
        {
            bmp.SetResolution(e.Graphics.DpiX, e.Graphics.DpiY);
            using (Graph开发者_如何转开发ics g = Graphics.FromImage(bmp))
            {
                g.ScaleTransform(e.Graphics.DpiX / 100, e.Graphics.DpiY / 100);
                drawStuff(g);
            }
            e.Graphics.DrawImageUnscaled(bmp, new Point(175, 50));
        }
    }

    private static void drawStuff(Graphics graphics)
    {
        Brush b1 = new SolidBrush(Color.LightGray);
        Brush b2 = new SolidBrush(Color.FromArgb(50, Color.Black));
        graphics.FillRectangle(b1, new Rectangle(0, 0, 100, 100));
        graphics.FillRectangle(b2, new Rectangle(25, 25, 50, 50));
    }
}


Could you use a library such as iTextSharp? The library has a bunch of different classes that will handle images and fonts.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号