简体   繁体   中英

C# Can't print the right image size

I'm trying to make a program that will print an image file to the printer onto an A4 sized paper. (The image is scaled to A4) This is currently the code I'm using.

Function.cs        

    Image tmp;
    public void PrintImage(string FileName)
    {
        tmp = Image.FromFile(FileName);
        PrintDocument printDoc = new PrintDocument();
        printDoc.DocumentName = "My Print Document";
        printDoc.PrintPage += new PrintPageEventHandler(OnPrintPage);
        // Send print message
        Console.WriteLine("Sending Print Message...");
        try
        {
            printDoc.Print();
        }
        catch(Exception)
        {
            Console.WriteLine("Error: No Printer Installed");
        }
        //
        // Event Handler
        //
    }
    private void OnPrintPage(object sender, PrintPageEventArgs ppea)
    {
    Console.WriteLine("Printing...");
    Graphics g = ppea.Graphics;
    g.DrawImage(tmp,0,0);
    }



Main.cs

    string ReceiptFilePath = "C:\\Receipt.jpg"; // The Image I want to print.

    private void button1_Click(object sender, EventArgs e)
    {
        functions.PrintImage(ReceiptFilePath);
    }

With the above code, it can be printed, however it is not in A4 size, rather it zoomed in almost 400%. How should I modify the code?

The image is scaled to A4

That's the problem statement. PrintDocument already scales. It initializes the Graphics instance you get from e.Graphics in the PrintPage event handler to PageUnit = GraphicsUnit.Display. Which is a precooked scaling mode that makes one pixel 0.01 inches on paper. Or in other words, an image that's 100 x 100 pixels becomes 1.00 x 1.00 inch on paper.

This is a convenient scaling mode, chosen to make anything you draw to the screen about the same size on paper. Video adapters tend to operate at 96 dots-per-inch resolution. Although that's changing, later Windows versions make it really easy to increase this.

So by prescaling the image, you'll end up making the image large. Which then makes it too large on paper by the additional scaling done by the printer's Graphics object.

Giving better advice isn't that easy since you didn't describe how you prescaled the image. Simply not prescaling probably already solves your problem. Using the Graphics.DrawImage(Image, Rectangle) overload can be a better bet, it gives you direct control over the size of the image on paper. Also giving you an opportunity to deal with different paper sizes and still making the image fit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM