0

I want to convert the WPF Controls view to PDF. I was able to convert it to PDF but it loses its style properties after converting to the PDF.

The text is being float to left but I have put it on the center on the WPF Window.

XAML Code:

<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>

My Code:

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;
    }
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • 1
    This code creates an XPS document first and then converts it to PDF. What does the *XPS* document look like? If that looks wrong, the PDF will also look wrong. – Panagiotis Kanavos Aug 09 '19 at 12:27
  • 1
    Render the visual to a bitmap using RenderTargetBitmap and then add the bitmap to the document. https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.imaging.rendertargetbitmap?redirectedfrom=MSDN&view=netframework-4.8 – J.H. Aug 09 '19 at 15:20

0 Answers0