將資料從印表機列印出來,其實是一個很煩雜的項目。微軟也開發了 FlowDocument 套件,此套件有人說好用,但本人發現其實超爛的。而且最近Win 10 更新後圖片都無法列印,所以並不建議使用 FlowDocument 。
目前最方便最好用的方式,就是先製作 pdf 檔,然後在視窗中將儲存的 pdf 顯示出來。
製作 pdf 文件最好用的套件就屬 iText 7。
安裝套件
首先從工具/NuGet 套件管理員/管理方案的NuGet套件,然後搜尋 iText 7 套件並進行安裝
簡易使用
首先從工
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using TextAlignment=iText.Layout.Properties.TextAlignment;
namespace pdf
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
string path = @"c:\temp";
Document doc;
string pdfFile;
PdfDocument pdf;
Paragraph paragraph;
public MainWindow()
{
InitializeComponent();
new Thread(Search).Start();
}
private void Window_Unloaded(object sender, RoutedEventArgs e)
{
web.Navigate("about:blank");
}
private void Search() {
pdfFile = DateTime.Now.ToString("yyyyMMddHHmmssffff");
pdf = new PdfDocument(new PdfWriter(string.Format("{0}/{1}.pdf", path, pdfFile)));
doc = new Document(pdf);
makePdf1();
makePdf2();
doc.Close();
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
psStack.Visibility = Visibility.Collapsed;
web.Navigate(string.Format("{0}/{1}.pdf", path, pdfFile));
}));
}
private void makePdf1()
{
pdf.SetDefaultPageSize(PageSize.A4);
doc.SetFont(PdfFontFactory.CreateFont("c:/Windows/Fonts/kaiu.ttf"));
paragraph = new Paragraph()
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Text("台北市政府新建工程處").SetFontSize(20))
.Add(new Text("\n第一頁").SetFontSize(16));
doc.Add(paragraph);
doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
}
private void makePdf2()
{
doc.SetFont(PdfFontFactory.CreateFont("c:/Windows/Fonts/kaiu.ttf"));
paragraph = new Paragraph()
.SetTextAlignment(TextAlignment.CENTER)
.Add(new Text("台北市政府新建工程處").SetFontSize(20))
.Add(new Text("\n第二頁").SetFontSize(16));
doc.Add(paragraph);
}
}
}

todo
