LoginSignup
2

More than 3 years have passed since last update.

WPF/C# で表示中の画像を A4 用紙いっぱいに印刷する

Posted at

WPF/C# でアプリケーション内に表示している画像を A4 用紙いっぱいに配置して印刷する方法です。
印刷方法については、こちらの記事 を参考にさせていただいてます。

事前準備

WPF アプリケーションのプロジェクトに「System.Printing」と「ReachFramework」の参照を追加します。

表示中の画像の印刷

WPF アプリケーションで System.Windows.Controls.Image クラスを使って画像を表示している場合、この ImageSource プロパティを渡すだけで表示中の画像が印刷されます。Viewbox を使っているので A4 用紙いっぱいに配置されます。

public static void PrintImage(ImageSource imageSource)
{
    using (var server = new LocalPrintServer())
    {
        // A4 縦の用紙を準備
        var queue = server.DefaultPrintQueue;
        var ticket = queue.DefaultPrintTicket;
        ticket.PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4);
        ticket.PageOrientation = PageOrientation.Portrait;

        // 印刷可能領域を取得
        var area = queue.GetPrintCapabilities().PageImageableArea;
        if (area == null) throw new Exception("印刷可能領域の取得に失敗 ...");

        // 用紙いっぱいにイメージを配置
        var page = new FixedPage();
        var viewBox = new Viewbox
        {
            Child = new Image { Source = imageSource },
            Margin = new Thickness(area.OriginWidth, area.OriginHeight, 0, 0),
            Width = area.ExtentWidth,
            Height = area.ExtentHeight,
            VerticalAlignment = VerticalAlignment.Top
        };
        page.Children.Add(viewBox);

        // デフォルトプリンタで印刷
        PrintQueue.CreateXpsDocumentWriter(queue).Write(page, ticket);
    }
}

こんな感じに。
印刷イメージ
ここでは仮想プリンタに出力して PDF で保存したんですが、実際のプリンタを「通常使うプリンターに設定」しておけば、このメソッドを呼ぶだけで直接、印刷されます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2