我想将 WPF 控件视图转换为 PDF。我能够将其转换为 PDF,但在转换为 PDF 后它会丢失其样式属性。
文本向左浮动,但我已将其放在 WPF 窗口的中心。
XAML 代码:
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" MaxHeight="842" Height="842" MinHeight="842" Width="832" >
<Grid>
<TextBlock Text="Hello World" HorizontalAlignment="Center"/>
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Content="Convert" Click="button_Click" Name="btn"/>
</Grid>
我的代码:
private void button_Click(object sender, RoutedEventArgs e)
{
var a = this.Width;
//TestPage fixedPage = new TestPage();
btn.Visibility = Visibility.Collapsed;
FixedDocument fixedDoc = new FixedDocument();
PageContent pageContent = new PageContent();
FixedPage fixedPage = new FixedPage();
PrintDialog printDlg = new PrintDialog();
Size pageSize = new Size(printDlg.PrintableAreaWidth, printDlg.PrintableAreaHeight - 100);
var visual = ((System.Windows.Controls.Panel)this.Content).Children[0] as UIElement;
((System.Windows.Controls.Panel)this.Content).Children.Remove(visual);
fixedPage.Children.Add(visual);
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
// write to PDF file
string tempFilename = "temp.xps";
File.Delete(tempFilename);
XpsDocument xpsd = new XpsDocument(tempFilename, FileAccess.ReadWrite);
System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
xw.Write(fixedDoc);
xpsd.Close();
PdfSharp.Xps.XpsConverter.Convert(tempFilename, "D:/testing.pdf", 1);
Process.Start("D:/testing.pdf");
btn.Visibility = Visibility.Visible;
}