How to convert XPS file to Bitmap using C#



How to convert XPS file to Bitmap

using System;
using System.IO;
using System.IO.Packaging;
using System.Windows.Documents;
using System.Windows.Xps.Packaging;
using System.Windows.Media.Imaging;
using System.Collections.Generic;  
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string xpsFile = "c:\\Completed-Form.xps";
                xpsToBmp(xpsFile);
                MessageBox.Show("Done");
            }
            catch (Exception ex)
            {
                MessageBox.Show (ex.Message);
            }
        }

        static public void xpsToBmp(string xpsFile)
        {
            XpsDocument xps = new XpsDocument(xpsFile, System.IO.FileAccess.Read);
            FixedDocumentSequence sequence = xps.GetFixedDocumentSequence();

                                                for (int pageCount = 0; pageCount <
sequence.DocumentPaginator.PageCount; ++pageCount)
            {
                DocumentPage page = sequence.DocumentPaginator.GetPage(pageCount);
                RenderTargetBitmap toBitmap = new RenderTargetBitmap((int)page.Size.Width,(int)
page.Size.Height,96,96,System.Windows.Media.PixelFormats.Default);

                toBitmap.Render(page.Visual);

                BitmapEncoder bmpEncoder = new BmpBitmapEncoder();
                bmpEncoder.Frames.Add(BitmapFrame.Create(toBitmap));

                FileStream fStream = new FileStream("c:\\xpstobmp" + pageCount + ".bmp",
FileMode.Create, FileAccess.Write);
                bmpEncoder.Save(fStream);
                fStream.Close();
            }
        }
    }
}

No comments:

Post a Comment