缩放图像以进行打印

时间:2010-08-15 20:05:56

标签: vb.net

我正在使用以下代码从PictureBox打印图像。 除了缩小图像(如果它们大于打印页面)以外,所有这些都很有效。 我有什么方法可以做到这一点吗?

屏幕截图,纸张边界外的大图片:

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

2 个答案:

答案 0 :(得分:5)

替换:

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

使用类似的东西来适应页面中的图像:

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,但我没有时间对其进行测试,如果您不理解我所做的事情,那么调试将会困难得多。很确定你会从仅仅代码中看到我想要做的事情!问候。

答案 1 :(得分:2)

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

是您需要解决的所有问题