Install-Package itext -Version 9.2.0;
Install-Package itext7.bouncy-castle-adapter;
//xaml
<Window x:Class="WpfApp59.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:WpfApp59"
mc:Ignorable="d"
WindowState="Maximized"
Title="MainWindow" Height="450" Width="800">
<Grid>
<DataGrid ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False"
FontSize="30"
HorizontalAlignment="Center"
HorizontalContentAlignment="Stretch"
VirtualizingPanel.IsVirtualizing="True"
CanUserAddRows="False">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="FontSize" Value="30"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="FontSize" Value="50"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" Width="Auto"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="Auto"/>
<DataGridTextColumn Header="Author" Binding="{Binding Author}" Width="Auto"/>
<DataGridTextColumn Header="Summary" Binding="{Binding Summary}" Width="Auto"/>
<DataGridTextColumn Header="Title" Binding="{Binding Title}" Width="Auto"/>
<DataGridTextColumn Header="Topic" Binding="{Binding Topic}" Width="Auto"/>
<DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}" Width="*"/>
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Export AS PDF"
Command="{Binding ExportASPDFCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource
Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
</Grid>
</Window>
//cs
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
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.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using Paragraph = iText.Layout.Element.Paragraph;
using Table = iText.Layout.Element.Table;
using TextAlignment = iText.Layout.Properties.TextAlignment;
namespace WpfApp59
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var vm = new MainVM(this);
this.DataContext=vm;
}
}
public class MainVM : INotifyPropertyChanged
{
private Window win;
private FrameworkElement fe;
PdfFont boldFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
public MainVM(Window winValue)
{
win = winValue;
if (win!=null)
{
win.Loaded+=Win_Loaded;
}
}
private void Win_Loaded(object sender, RoutedEventArgs e)
{
var tempFe = win.Content as FrameworkElement;
if (tempFe==null)
{
return;
}
fe=tempFe;
InitData();
}
private void InitData()
{
BooksCollection=new ObservableCollection<Book>();
for (int i = 0; i<100000; i++)
{
BooksCollection.Add(new Book()
{
Id=i+1,
Name=$"Name_{i+1}",
Author=$"Author_{i+1}",
ISBN=$"{Guid.NewGuid().ToString("N")}_{i+1}",
Summary=$"Summary_{i+1}",
Title=$"Title_{i+1}",
Topic=$"Topic_{i+1}"
});
}
}
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propName = "")
{
var handler = PropertyChanged;
if (handler!=null)
{
handler?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
private ObservableCollection<Book> booksCollection;
public ObservableCollection<Book> BooksCollection
{
get
{
return booksCollection;
}
set
{
if (value!=booksCollection)
{
booksCollection = value;
OnPropertyChanged();
}
}
}
private ICommand exportASPDFCommand;
public ICommand ExportASPDFCommand
{
get
{
if (exportASPDFCommand==null)
{
exportASPDFCommand=new DelCommand(ExportASPDFCommandExecuted);
}
return exportASPDFCommand;
}
}
private void ExportASPDFCommandExecuted(object? obj)
{
var dg = obj as DataGrid;
if (dg==null)
{
return;
}
Task.Run(() =>
{
var itemsList = dg.Items.Cast<Book>().ToList();
string pdfFileName = $"Export_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.pdf";
Thread exportThread = new Thread(() =>
{
ExportListTDataInPDF<Book>(pdfFileName, itemsList);
});
exportThread.Start();
exportThread.Join();
var proc = new Process()
{
StartInfo=new ProcessStartInfo()
{
FileName=pdfFileName,
UseShellExecute=true,
}
};
proc.Start();
});
}
public void ExportListTDataInPDF<T>(string pdfFileName, List<T> dataList)
{
using (var pdfWriter = new PdfWriter(pdfFileName))
{
using (var pdfDoc = new PdfDocument(pdfWriter))
{
var doc = new Document(pdfDoc, PageSize.A1);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
Paragraph paragraph = new Paragraph("Items From DataGrid")
.SetFont(font)
.SetFontSize(150)
.SetFontColor(ColorConstants.BLACK)
.SetTextAlignment(TextAlignment.CENTER);
doc.Add(paragraph);
var props = typeof(T).GetProperties();
var columnNames = props.Select(x => x.Name)?.ToList();
Table table = new Table(columnNames.Count, false);
table.SetWidth(UnitValue.CreatePercentValue(100));
foreach (var col in columnNames)
{
table.AddHeaderCell(new Cell().Add(new Paragraph(col)
.SimulateBold()
.SetTextAlignment(TextAlignment.CENTER))
.SetFontSize(50));
}
foreach (var item in dataList)
{
foreach(var prop in props)
{
var strValue = prop.GetValue(item)?.ToString()??string.Empty;
table.AddCell(new Cell().Add(new Paragraph(strValue).SetFontSize(30)));
}
}
doc.Add(table);
doc.Close();
}
}
}
}
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public string Summary { get; set; }
public string Title { get; set; }
public string Topic { get; set; }
}
public class DelCommand : ICommand
{
private Action<object?> execute;
private Predicate<object?> canExecute;
public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue = null)
{
execute= executeValue;
canExecute= canExecuteValue;
}
public event EventHandler? CanExecuteChanged
{
add
{
CommandManager.RequerySuggested+=value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
public bool CanExecute(object? parameter)
{
return canExecute==null ? true : canExecute(parameter);
}
public void Execute(object? parameter)
{
execute(parameter);
}
}
}
![image]()
![image]()
![image]()