この記事は2019年06月25日に投稿しました。
目次

エッセンシャルWPF:Windows Presentation Foundation (Programmer's SELECTION)
- 作者: Chris Anderson,星睦
- 出版社/メーカー: 翔泳社
- 発売日: 2007/10/31
- メディア: 大型本
- 購入: 6人 クリック: 128回
- この商品を含むブログ (32件) を見る
1. はじめに
こんにちは、iOSのエディタアプリPWEditorの開発者の二俣です。
今回は業務で使用しているWPFで印刷処理を行う方法についてです。
2. WPFで印刷処理を行う
WPFで印刷処理を行う方法ですが、以下のような実装になります。
実装例
MainWindow.xaml
<Window x:Class="WPFPrint.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WPFPrint" mc:Ignorable="d" Title="印刷サンプル" Height="200" Width="300 "> <Grid> <Button x:Name="btnPrint" Content="印刷" HorizontalAlignment="Center" VerticalAlignment="center" Width="75" Click="BtnPrint_Click"/> </Grid> </Window>
MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Printing; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WPFPrint { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void BtnPrint_Click(object sender, RoutedEventArgs e) { // 印刷ダイアログを表示します。 var printDialog = new PrintDialog(); var result = printDialog.ShowDialog(); // 印刷ボタン以外が押下された場合、処理を終了します。 if (!result.HasValue || !result.Value) return; // 印刷データを生成します。 var textBlock = new TextBlock(); textBlock.Text = "テスト"; textBlock.FontSize = 16; var canvas = new Canvas(); Canvas.SetTop(textBlock, 100); Canvas.SetLeft(textBlock, 100); canvas.Children.Add(textBlock); var page = new FixedPage(); page.Children.Add(canvas); // 印刷します。 var queue = printDialog.PrintQueue; var writer = PrintQueue.CreateXpsDocumentWriter(queue); writer.Write(page); } } }
3. おわりに
現在作成しているWPFのアプリで印刷処理があるため、印刷の方法を調査しました。
文字列を印刷するだけならば上記の実装でできるようです。
いろいろ細かく指定したい場合、設定方法があると思いますが、それはおいおい調査したいと思います。

実戦で役立つ C#プログラミングのイディオム/定石&パターン
- 作者: 出井秀行
- 出版社/メーカー: 技術評論社
- 発売日: 2017/02/18
- メディア: 大型本
- この商品を含むブログ (1件) を見る
紹介している一部の記事のコードはGitlabで公開しています。
興味のある方は覗いてみてください。
私が勤務しているニューラルでは、主に組み込み系ソフトの開発を行っております。
弊社製品のハイブリッドOS Bi-OSは高い技術力を評価されており、特に制御系や通信系を得意としています。
私自身はiOSモバイルアプリやウィンドウズアプリを得意としております。
ソフトウェア開発に関して相談などございましたら、お気軽にご連絡ください。
また一緒に働きたい技術者の方も随時募集中です。
興味がありましたらご連絡ください。
EMAIL : info-nr@newral.co.jp / m-futamata@newral.co.jp
TEL : 042-523-3663
FAX : 042-540-1688