简体   繁体   English

wpf-如何使用PDFSharp将整个页面打印为pdf

[英]wpf - how to print a whole page to pdf with PDFSharp

So I want to know how to print my entire WPF page to a PDF file with PDFSharp. 所以我想知道如何使用PDFSharp将我的整个WPF页面打印到PDF文件中。 I've already been looking at several articles but I can't seem to figure it out. 我已经看过几篇文章,但似乎无法弄清楚。 I want the pdf to look something like this: 我希望pdf看起来像这样: 在此处输入图片说明

I've already looked up on articles about drawing strings, lines name it. 我已经看过有关绘制字符串的文章,请用线条命名。 But creating every line, string and shape individually looks like a sloppy and bad idea to me. 但是,对我来说,单独创建每条线,线和形状似乎是一个草率而不好的主意。

Can anyone help me with this? 谁能帮我这个?

Articles will also be appreciated! 文章也将不胜感激!

Thanks in advance 提前致谢

I Would say first export your control to image with RenderTargetBitmap and then use a library to export it to PDF. 我要说的是先使用RenderTargetBitmap将控件导出到图像,然后使用库将其导出到PDF。

Maybe this sample might help ? 也许此示例可能会有所帮助?

http://www.techcognition.com/post/Create-PDF-File-From-WPF-Window-using-iTextsharp-1001 http://www.techcognition.com/post/Create-PDF-File-From-WPF-Window-using-iTextsharp-1001

With this library 有了这个图书馆

Here his the Control to Image class I'm using with sucess (I'm able to get a PNG snapshot of complex UI controls implying a very deep parent-child hierarchy) 这是我正在成功使用的Control to Image类(我可以获得复杂的UI控件的PNG快照,这暗示着非常深的父子层次结构)

The source is a WPF control container (usercontrol, grid, wahtever). source是WPF控件容器(usercontrol,grid,wahtever)。

The path is the full path for PNG output file (C:\\Temp\\myImage.png) path是PNG输出文件的完整路径(C:\\ Temp \\ myImage.png)

public class ControlToImageSnapshot
{
    /// <summary>
    /// Conversion du controle en image PNG
    /// </summary>
    /// <param name="source">Contrôle à exporter</param>
    /// <param name="path">Destination de l'export</param>
    /// <param name="zoom">Taille désirée</param>
    public static void SnapShotPng(FrameworkElement source, string path, double zoom = 1.0)
    {
        try
        {
            var dir = Path.GetDirectoryName(path);
            if (dir != null && !Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)source.ActualWidth, (int)source.ActualHeight, 96, 96, PixelFormats.Pbgra32);
            VisualBrush sourceBrush = new VisualBrush(source);


            DrawingVisual drawingVisual = new DrawingVisual();

            DrawingContext drawingContext = drawingVisual.RenderOpen();

            using (drawingContext)
            {

                drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(source.ActualWidth, source.ActualHeight)));
            }
            renderTarget.Render(drawingVisual);

            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(renderTarget));

            using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                encoder.Save(stream);
            }

            createPdfFromImage(path, @"C:\Temp\myfile.pdf");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    public static void createPdfFromImage(string imageFile, string pdfFile)
    {
        using (var ms = new MemoryStream())
        {
            var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER.Rotate(), 0, 0, 0, 0);
            PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create));
            iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
            document.Open();

            FileStream fs = new FileStream(imageFile, FileMode.Open);
            var image = iTextSharp.text.Image.GetInstance(fs);
            image.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
            document.Add(image);
            document.Close();

            //open pdf file
            Process.Start("explorer.exe", pdfFile);
        }
    }
}

For pdfsharp its quite easy, you can pass in an array of bytes for the pdf image and pdf, ive used this function quite a lot when dealing with images in pdfsharp. 对于pdfsharp来说,它非常容易,您可以为pdf图像和pdf输入一个字节数组,我在处理pdfsharp中的图像时就大量使用了此功能。

fairly self explanatory 相当自我解释

Open pdf and the image into a memorystream 打开pdf并将图像存入内存流

Get pdf setup and choose page to draw on I always set interpolate to false, I get better results with the kind of images I'm dealing with, if you have shading in your image set it to true. 获取pdf设置并选择要绘制的页面我总是将interpolate设置为false,如果要处理阴影,请将其设置为true,可以得到更好的效果。

then all your left to do is draw the image on the pdf and return as a memorystream 那么您剩下要做的就是在pdf上绘制图像并作为记忆流返回

    public static byte[] AddImageToPdf(byte[] pdf, byte[] img, double x, double y)
    {
        using (var msPdf = new MemoryStream(pdf))
        {
            using (var msImg = new MemoryStream(img))
            {
                var image = Image.FromStream(msImg);

                var document = PdfReader.Open(msPdf);
                var page = document.Pages[0];
                var gfx = XGraphics.FromPdfPage(page);

                var ximg = XImage.FromGdiPlusImage(image);
                ximg.Interpolate = false;

                gfx.DrawImage(
                    ximg,
                    XUnit.FromCentimeter(x),
                    XUnit.FromCentimeter(y),
                    ximg.PixelWidth * 72 / ximg.HorizontalResolution,
                    ximg.PixelHeight * 72 / ximg.HorizontalResolution);


                using (var msFinal = new MemoryStream())
                {
                    document.Save(msFinal);
                    return msFinal.ToArray();
                }
            }
        }
    }

its hardcoded for page 1 in the pdf, easily extendable to pass in pages if you want, ill leave that as an exercise for yourself, at the end you get a nice byte array containing your pdf, no files need to touch the ground enroute if you import your image as a memorystream from your control and pass it in. another answer in this topic has a good way of getting the control image. 它在pdf中为第1页进行了硬编码,如果您愿意,可以轻松扩展以传递页面,请您自己做一个练习,最后得到一个包含pdf的漂亮字节数组,如果在运行时没有文件需要接触地面您可以从控件中将图像导入为内存流并将其传递。本主题中的另一个答案是获取控件图像的好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM