Saving a wpf layout to pdf using pdfsharp, c#

独自空忆成欢 提交于 2021-02-17 20:55:39

问题


I'm new to c#, wpf and the pdfsharp library. This is my XAML Code:

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

I want now save my "graphLayout" to a pdf-file using Pdfsharp. I created a button and used basically the "hello world" sample code in the pdfsharp wiki to start.

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

I get a pdf , but there is just the text in it. Can somebody tell me please, how i can save the whole layout into a pdf? thanks


回答1:


Read documentations: http://www.pdfsharp.net/wiki/Graphics.ashx?AspxAutoDetectCookieSupport=1

I am not aware that you can convert directly from WPF to PDF, however it's pretty simple

with WPF<-->XPS<-->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);

where dp is your Visual/layout

sources:

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

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



来源:https://stackoverflow.com/questions/20372379/saving-a-wpf-layout-to-pdf-using-pdfsharp-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!