Image scaling for printing

I am using the following code to print an image from a PictureBox. Everything works fine except for scaling images down if they are larger than the print page. Is there a way that I'm missing for this?

Screenshot, large image outside the borders of the document:

http://a.yfrog.com/img46/63/problemsh.png http://a.yfrog.com/img46/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
+3
source share
2 answers

Replace:

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

With something similar to fit the image on 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) 

scalefac, , , , . , , ! .

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

- ,

+2

Source: https://habr.com/ru/post/1759801/


All Articles