Canvas print - wpf

丶灬走出姿态 提交于 2019-12-25 01:37:29

问题


I used these code in order to print out the UI. Printing out is working, but if the size of paper is over, the UI cuts off in the middle of a canvas.

Is there any possible way not to be cut off in the middle?

<--cs code-->

PrintDialog dialog = new PrintDialog();
dialog.PrintVisual(lst , "print");

<--Xaml -->

<ListView Name="lst">
    <Grid Name="grdPrint">
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>

        <Canvas  Grid.Row="0"    >
           .......
        </Canvas>

        <HListBox x:Name="lstImage" ItemsSource="{Binding IMG, Mode=TwoWay}" Grid.Row="1" IsHitTestVisible="True">
            <HListBox.ItemTemplate>
                <DataTemplate>
                    <HImage Margin="0"  Width="590"  Height="590" Stretch="Fill" Source="{Binding IMG_PATH_NM, Converter={StaticResource StrUriConverter}}" Tag="{Binding IMG_PATH_NM}">
                    </HImage>
                </DataTemplate>
            </HListBox.ItemTemplate>
            <HListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Vertical" HorizontalAlignment="Center"  IsHitTestVisible="True"/>
                </ItemsPanelTemplate>
            </HListBox.ItemsPanel>
        </HListBox>
    </Grid>
</ListView>

回答1:


This method will print the canvas to PNG file.

public void ExportToPNG(string imgpath, Canvas surface)
{
    Uri path = new Uri(imgpath);

    if (path == null)
        return;
    Transform transform = surface.LayoutTransform;
    surface.LayoutTransform = null;

    Size size = new Size(surface.Width, surface.Height);
    surface.Measure(size);
    surface.Arrange(new Rect(size));

    RenderTargetBitmap renderBitmap =
        new RenderTargetBitmap(
        (int)size.Width,
        (int)size.Height,
        96d,
        96d,
        PixelFormats.Pbgra32);
    renderBitmap.Render(surface);

    using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
    {
        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
        encoder.Save(outStream);
    }
    surface.LayoutTransform = transform;
}



回答2:


You could create an BitmapImage (see RenderTargetBitmap to create a bitmap from an element). This bitmap can then be saved as a JPEG file and manipulated using GDI+ (System.Image).



来源:https://stackoverflow.com/questions/14152308/canvas-print-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!