(C#) xps to png

C#/Winform 2018. 2. 24. 11:08
728x90
728x170

       

 xps 파일을  png 파일로 변경하는 코드

        public int XpsToPng(string xps_file)
        {
            // Make sure this is an xps file.
            if (!xps_file.ToLower().EndsWith(".xps"))
                throw new ArgumentException(
                    "Method XpsToPng only works for .xps files.");

            // Get the file's name without the .xps on the end.
            string file_prefix =
                xps_file.Substring(0, xps_file.Length - 4);

            // Load the XPS document.
            XpsDocument xps_doc = new XpsDocument(xps_file, FileAccess.Read);

            // Get a fixed paginator for the document.
            IDocumentPaginatorSource page_source =  xps_doc.GetFixedDocumentSequence();
            DocumentPaginator paginator =  page_source.DocumentPaginator;

            // Process the document's pages.
            int num_pages = paginator.PageCount;
            for (int i = 0; i < num_pages; i++)
            {
                using (DocumentPage page = paginator.GetPage(i))
                {
                    // Render the page into the memory stream.
                    int width = (int)page.Size.Width;
                    int height = (int)page.Size.Height;
                    RenderTargetBitmap bitmap =
                        new RenderTargetBitmap(
                            width, height, 96, 96,
                            PixelFormats.Default);
                    bitmap.Render(page.Visual);

                    // Save the PNG file.
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bitmap));

                    using (MemoryStream stream = new MemoryStream())
                    {
                        encoder.Save(stream);

                        using (FileStream file = new FileStream(
                            file_prefix + (i + 1).ToString() + ".png",
                            FileMode.Create))
                        {
                            file.Write(stream.GetBuffer(), 0,
                                (int)stream.Length);
                            file.Close();
                        }
                    }
                }
            }
            return num_pages;
        }

728x90
그리드형
Posted by kjun.kr
,