打印图像而不是ByteArray

本文关键字:ByteArray 图像 打印 | 更新日期: 2023-09-27 18:00:35

我想我在打印文件时错过了一些东西。我从png图像中读取所有字节,并将它们发送到打印机的作业流。然而,我打印出的是字节,而不是图像本身。我想我需要合适的打印格式。

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

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

有什么想法吗?

打印图像而不是ByteArray

向打印机发送原始数据并不意味着将文件的内容转储到打印机队列。若要将原始数据发送到打印机,您需要发送PCL、PS或其他类似数据,这些数据会"告诉"打印机如何打印您的文档。

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

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

使用PrintDocument打印图像。如何调整图像以适应纸张尺寸

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

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

    //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)
        {
        }
    }