使用pdfsharp将wpf布局保存为pdf,c#

时间:2013-12-04 10:08:43

标签: c# wpf graph pdfsharp quickgraph

我是c#,wpf和pdfsharp库的新手。 这是我的XAML代码:

<Grid>
    <zoom:ZoomControl>
    <graphsharp:GraphLayout x:Name="graphLayout"
                            Graph="{Binding ElementName=root, Path=GraphToVisualize}" 
                            LayoutAlgorithmType="FR"
                            OverlapRemovalAlgorithmType="FSA"
                            HighlightAlgorithmType="Simple"></graphsharp:GraphLayout>
    </zoom:ZoomControl>
    <Button Content="Button" Height="23" Name="button1" Width="75" Margin="12,294,658,412" Click="button1_Click" />
</Grid>

我现在想用Pdfsharp将我的“graphLayout”保存到pdf文件中。我创建了一个按钮,基本上使用了pdfsharp wiki中的“hello world”示例代码来启动。

PdfDocument document = new PdfDocument();
        document.Info.Title = "Created with PDFsharp";
        PdfPage page = document.AddPage(); 
        XGraphics gfx = XGraphics.FromPdfPage(page);
        XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
        gfx.DrawString("My Graph", font, XBrushes.Black,
            new XRect(0, 0, page.Width, page.Height),
            XStringFormats.TopCenter);
        const string filename = "MyGraph.pdf";
        document.Save(graphLayout+filename);
        Process.Start(filename);

我得到一个pdf,但其中只有文字。有人可以告诉我,我如何将整个布局保存为PDF格式? 感谢

1 个答案:

答案 0 :(得分:10)

阅读文档:http://www.pdfsharp.net/wiki/Graphics.ashx?AspxAutoDetectCookieSupport=1

我不知道您可以直接从WPF转换为PDF,但这很简单

使用WPF&lt; - &gt; XPS&lt; - &gt; PDF。

MemoryStream lMemoryStream = new MemoryStream();
Package package = Package.Open(lMemoryStream, FileMode.Create);
XpsDocument doc = new XpsDocument(package);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
writer.Write(dp);
doc.Close();
package.Close();

var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream);
PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, d.FileName, 0);

其中dp是您的Visual / layout

来源:

http://www.nathanpjones.com/wp/2013/03/output-to-pdf-in-wpf-for-free/

http://www.pdfsharp.net/wiki/PDFsharpSamples.ashx