C# Graphics.DrawImage 打印时截断/裁剪图像

发布于 2025-01-09 09:42:48 字数 2544 浏览 1 评论 0原文

我正在尝试用 C# 打印图像。问题是打印时图像被裁剪/截断。分辨率和宽度/高度是正确的,因为 2 个边框与打印页面匹配,但图像只打印了一半。

打印图像:打印图像 预期图像: 预期图像

该图像是 6''x5'' (152.4 mm x 127mm),但我可以将图像转换为 .tiff (同样的问题)。打印机选择了正确的纸张。如果我将 png 转换为 pdf 并使用 Adob​​e Reader 打印它,我没有任何问题(没有 C#)

这是代码的一部分(实现是一个类,但只是变量初始化)

private void PD_PrintPage(object sender, PrintPageEventArgs e)
{
    try
    {
        if (e != null)
        {
            PD_PrintPage_DrawImage(e);
            PD_PrintPage_Close(e);
        }
    }
    catch (Exception)
    {
        // Error handling.
        e.HasMorePages = false;
        e.Cancel = true;
        _exceptionFlag = true;
    }
}
public Print(String devName, String portName, int totalPrintPage)
{
    try
    {
        // Create the PrintDocumentObject.
        _pdPrint = new PrintDocument();

        // Add the PrintPageEventHandler.
        _pdPrint.PrintPage += new PrintPageEventHandler(PD_PrintPage);

        // Set the using Printer.
        _pdPrint.PrinterSettings.PrinterName = devName;
        _pdPrint.DocumentName = "Label Print";

        _totalPrintPage = 1;        
        
        return;
    }
    catch
    {
        throw;
    }
}

public void DoPrinting()
{
    try
    {
        _pdPrint.Print();
        if(_exceptionFlag == true)
        {
            throw new Exception();
        }
    }
    catch (Exception)
    {
        throw;
    }
}

private void PD_PrintPage_DrawImage(PrintPageEventArgs e)
{
    try
    {
        float width = 152.4F;
        float height = 127.0F;

        // Set page unit.
        e.Graphics.PageUnit = GraphicsUnit.Millimeter;
        
        // String currentDirectryPath = Directory.GetCurrentDirectory();
        String imageFilePath = "C:\\Users\\uservm\\Documents\\interfaces\\label6x5.png";

        //String imageFilePath = Path.Combine(currentDirectryPath, imageFileName);

        using (FileStream fs = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
        using (Image img = Image.FromStream(fs))
        {
            // Draw image.

            e.Graphics.DrawImage(img, 0, 0, width, height);
        }
    }
    catch (Exception)
    {
        // Error handling.
        MessageString.GetSystemError((int)MessageString.STATE_DRAWIMAGE_ERROR);
    }
}

new Rectangel() 方法仅接受 int 作为变量,但我的页面大小是 float。不过,我如何在我的功能上实现它?我认为问题在于绘图区域未满。

有什么想法吗?

Im trying to print an image with C#. The problem is that the image is cropped/truncated when printing. The resolution and width/height are correct since 2 borders match the printed page, but the image is only printed by half.

Printed Image: Printed Image
Expected Image: Expected Image

The image is a .png of 6''x5'' (152.4mm x 127mm) but i can convert the image to .tiff (same issue). The printer has the correct paper selected. If i convert the png to pdf and print it with Adobe Reader i have no issues (without C#)

This is part of the code (the implementation is a Class but is only variable initialization)

private void PD_PrintPage(object sender, PrintPageEventArgs e)
{
    try
    {
        if (e != null)
        {
            PD_PrintPage_DrawImage(e);
            PD_PrintPage_Close(e);
        }
    }
    catch (Exception)
    {
        // Error handling.
        e.HasMorePages = false;
        e.Cancel = true;
        _exceptionFlag = true;
    }
}
public Print(String devName, String portName, int totalPrintPage)
{
    try
    {
        // Create the PrintDocumentObject.
        _pdPrint = new PrintDocument();

        // Add the PrintPageEventHandler.
        _pdPrint.PrintPage += new PrintPageEventHandler(PD_PrintPage);

        // Set the using Printer.
        _pdPrint.PrinterSettings.PrinterName = devName;
        _pdPrint.DocumentName = "Label Print";

        _totalPrintPage = 1;        
        
        return;
    }
    catch
    {
        throw;
    }
}

public void DoPrinting()
{
    try
    {
        _pdPrint.Print();
        if(_exceptionFlag == true)
        {
            throw new Exception();
        }
    }
    catch (Exception)
    {
        throw;
    }
}

private void PD_PrintPage_DrawImage(PrintPageEventArgs e)
{
    try
    {
        float width = 152.4F;
        float height = 127.0F;

        // Set page unit.
        e.Graphics.PageUnit = GraphicsUnit.Millimeter;
        
        // String currentDirectryPath = Directory.GetCurrentDirectory();
        String imageFilePath = "C:\\Users\\uservm\\Documents\\interfaces\\label6x5.png";

        //String imageFilePath = Path.Combine(currentDirectryPath, imageFileName);

        using (FileStream fs = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
        using (Image img = Image.FromStream(fs))
        {
            // Draw image.

            e.Graphics.DrawImage(img, 0, 0, width, height);
        }
    }
    catch (Exception)
    {
        // Error handling.
        MessageString.GetSystemError((int)MessageString.STATE_DRAWIMAGE_ERROR);
    }
}

The new Rectangel() method only accepts int as variable but my page size is float. Still, how do i implement it on my funcion? I think the issue is that the draw area is not full.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一杯敬自由 2025-01-16 09:42:48

这种类型的结果或更糟糕的其他格式通常是由于表单定义中的问题造成的,通常在 Windows 默认的纵向和尺寸较小的页面上打印横向屏幕时出现。这是完全相同的测试打印输入,但有两种不同的纸张输出类型。

输入图片此处描述

Acrobat 是由印刷厂专家编写的(与 Microsoft 不同),因此他们的纸张输出通常更符合预期。分辨率的关键是确保所有单位都已知,并且您发布的图像是无单位的,因此不是 6 x 5,如果设置为 100 dpi,则几乎是 6 x 5(x 和 y 上的一个像素),所以如果设置为 100 dpi,可能会有所帮助至 101 dpi。或者最好使用 576 宽和 480 高的比例,在许多应用程序中默认为 6X5。还要仔细检查 Windows 打印管理认为页面布局应该是什么,例如确保将其设置为无边框以及打印机驱动程序的正确方向,因为有些会使用与正常成 90 度的卷筒送纸。

如果您的 FORMS 设置正确,那么在任何方向打印完整介质应该没有问题,因此这里我定义了 6x5 和 5x6,这就是测量的输出:

在此处输入图像描述

尝试不同的小型专业驱动程序可能会有所帮助, 因此对于标签,通常建议使用"Bartender Seagull" 驱动程序(如果适用于该打印机型号)。

免责声明:我支持 SumatraPDF,并且可以对其进行修改以适合您的打印,但是对于小格式来说这不是一个简单的任务,并且通常需要大量覆盖 Windows 默认设置。最重要的是不要使用 -silent 开关,尤其是在打印服务时。

输入图片此处描述

注意,我必须在 Windows 打印管理中添加一个 6x5 表单,尽管它显示为 6.00x5.00,但它实际上被定义为 5 英寸宽 x 6 英寸高!因为您希望将其应用为横向旋转。然后,我必须确保驱动程序默认设置为横向,如果需要无头旋转,它可能会失败。所以现在我的媒体结构为 paperkind=138 (每台机器上的数字都会不同,我可以使用设置 paper=6x5,这也有效)对于某些驱动程序媒体列表来说编号更可靠。另外,因为我们知道您的图像太大,所以我需要添加收缩。到目前为止,使用 Acrobat 的默认设置比使用 Microsoft 的默认设置更容易,并且 Acrobat 可以在待机 (/T) 状态下运行,因此不需要为每次打印缓慢地重新加载。

That type of result or worse with other formats is normally a result of problems in the form definition, commonly seen when printing a landscape screen on a Windows default of portrait and an undersized page. Here is exactly same test print input but two different paper output types.

enter image description here

Acrobat is written by a print house specialist (unlike Microsoft) so their paper output is usually more what's expected. The key to resolution is ensuring all units are known and the image you posted is unit-less thus not 6 x 5 which it would almost be (a pixel over in x and y) if set to 100 dpi so perhaps it may help if set to 101 dpi. OR better yet use a ratio of 576 wide and 480 high which will default to 6X5 in many apps. Also double check what windows print management thinks that page layout should be e.g. ensure it is set to borderless and the correct orientation for the printer driver since some will use roll feed at 90 degrees to normal.

If your FORMS are set correctly it should be no problem printing full media at any orientation so here I defined 6x5 and 5x6 and that is the measured output:

enter image description here

It may help to try a different small format specialist driver, thus for labels "Bartender Seagull" drivers (if available for that printer model) are often recommended.

Disclaimer: I support SumatraPDF and that could be modified to suit your printing, HOWEVER it is not a simple task for small formats and usually requires much overriding of windows default settings. Most important DO NOT use -silent switch, especially when print serving.

enter image description here

Note I had to add a 6x5 Form in Windows print management, and obscurely that is actually defined as 5 inches wide by 6 inches high even though it says 6.00x5.00 ! since you want it to be applied rotated as Landscape. I then have to ensure the driver is set to Landscape by default, it is likely to fail if needing headless rotation. So now I have my Media structure as paperkind=138 (the number will be different on every machine and I could use setting paper=6x5, which did work too) numbering is more reliable for some drivers media lists. Also since we know your image is oversized I need to add shrink. By far it is easier to use Acrobat's defaults rather than Microsoft's, and Acrobat can be left running in standby (/T) so it does not need to slowly reload for each print.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文