开发者

Scaling image for printing

开发者 https://www.devze.com 2023-01-11 11:02 出处:网络
I\'m using the following code to print an image from a PictureBox. All works great except for scaling images down if they are bigger than the print page.

I'm using the following code to print an image from a PictureBox. All works great except for scaling images down if they are bigger than the print page. Is there a method I'm missing to do this?

Screenshot, large image outside of the paper bounds:

http://a.yfrog.com/img46/63/problemsh.png http://a.yfrog.com/im开发者_如何学JAVAg46/63/problemsh.png

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    AddHandler PrintDocument1.PrintPage, AddressOf OnPrintPage

    With PageSetupDialog1
        .Document = PrintDocument1
        .PageSettings = PrintDocument1.DefaultPageSettings

        If PictureEdit1.Image.Height >= PictureEdit1.Image.Width Then
            PageSetupDialog1.PageSettings.Landscape = False
        Else
            PageSetupDialog1.PageSettings.Landscape = True
        End If

    End With

    PrintDialog1.UseEXDialog = True
    PrintDialog1.Document = PrintDocument1

    If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        PrintPreviewDialog1.Document = PrintDocument1
        If PrintPreviewDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

            PrintDocument1.DefaultPageSettings = PageSetupDialog1.PageSettings
            PrintDocument1.Print()

        End If
    End If
End Sub

Private Sub OnPrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
    Dim img As Image = PictureEdit1.Image

    Dim sz As New SizeF(100 * img.Width / img.HorizontalResolution, 100 * img.Height / img.VerticalResolution)
    Dim p As New PointF((e.PageBounds.Width - sz.Width) / 2, (e.PageBounds.Height - sz.Height) / 2)
    e.Graphics.DrawImage(img, p)
End Sub


Replace:

Dim sz As New SizeF(100 * img.Width / img.HorizontalResolution, 100 * img.Height / img.VerticalResolution) 

With something like this to fit the image in the page:

dim ScaleFac as integer = 100
While (ScaleFac * img.Width / img.HorizontalResolution > e.PageBounds.Width or ScaleFac * img.Height / img.VerticalResolution > e.PageBounds.Height) and ScaleFac > 2
    ScaleFac -= 1
Wend
Dim sz As New SizeF(ScaleFac * img.Width / img.HorizontalResolution, ScaleFac* img.Height / img.VerticalResolution) 

You could use algebra to solve for the proper scalefac, but I don't have time to test it and if you didn't understand what I'd done that would be a lot harder for you to debug. Pretty sure you'll see what I'm trying to do here from the just the code alone! Regards.


Dim img As Image = PictureEdit1.Image
e.Graphics.DrawImage(img, 0, 0, 
                     e.PageBounds.Width, e.PageBounds.Height)

is all that you will need to solve

0

精彩评论

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