打印图像而不是ByteArray

时间:2014-04-29 07:23:17

标签: c#

我想在打印文件时我会想念一些东西。我从png图像中读取所有字节并将它们发送到打印机的作业流。但是我打印出字节而不是图像本身。我想我需要正确的打印格式。

这是包含我正在使用的代码的链接:

http://support.microsoft.com/kb/322091/en

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

将原始数据发送到打印机并不意味着只是将文件内容转储到打印机队列。要将原始数据发送到打印机,您需要发送PCL,PS或其他一些等效数据,告诉打印机如何打印文档。

您可能需要使用System.Drawing.Printing.PrintDocument类。

编辑:有一个很好的例子,说明如何在SO上打印图像:

Printing image with PrintDocument. how to adjust the image to fit paper size

PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PrinterSettings.PrinterName = "Printer Name";
pd.DefaultPageSettings.Landscape = true; //or false!
pd.PrintPage += (sender, args) =>
{
    Image i = Image.FromFile(@"C:\...\...\image.jpg");
    Rectangle m = args.MarginBounds;

    if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
    {
        m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
    }
    else
    {
        m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
    }
    args.Graphics.DrawImage(i, m);
};
pd.Print();

答案 1 :(得分:0)

我想你可以在这里使用我的代码:

    //Print Button Event Handeler
    private void btnPrint_Click(object sender, EventArgs e)
    {
        PrintDocument pd = new PrintDocument();
        pd.PrintPage += PrintPage;
        //here to select the printer attached to user PC
        PrintDialog printDialog1 = new PrintDialog();
        printDialog1.Document = pd;
        DialogResult result = printDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            pd.Print();//this will trigger the Print Event handeler PrintPage
        }
    }

    //The Print Event handeler
    private void PrintPage(object o, PrintPageEventArgs e)
    {
        try
        {
            if (File.Exists(this.ImagePath))
            {
                //Load the image from the file
                System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");

                //Adjust the size of the image to the page to print the full image without loosing any part of it
                Rectangle m = e.MarginBounds;

                if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
                {
                    m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
                }
                else
                {
                    m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
                }
                e.Graphics.DrawImage(img, m);
            }
        }
        catch (Exception)
        {

        }
    }