예제 #1
0
        private void ConvertImages_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (officeFileOpen_Status)
                {
                    FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
                    DialogResult        result = folderBrowserDialog1.ShowDialog();
                    string localpath           = String.Empty;
                    localpath = folderBrowserDialog1.SelectedPath;

                    FixedDocumentSequence seq;
                    seq = xpsDoc.GetFixedDocumentSequence();
                    DocumentPaginator paginator = seq.DocumentPaginator;
                    //// I only want the all page for this example
                    for (int i = 0; i < paginator.PageCount; i++)
                    {
                        Visual           visual = paginator.GetPage(i).Visual;
                        FrameworkElement fe     = (FrameworkElement)visual;
                        int    multiplyFactor   = 4;
                        string outputPath       = localpath + "\\page" + i + ".png";
                        Console.WriteLine(localpath);
                        RenderTargetBitmap bmp = new RenderTargetBitmap(
                            (int)fe.ActualWidth * multiplyFactor,
                            (int)fe.ActualHeight * multiplyFactor,
                            96d * multiplyFactor,
                            96d * multiplyFactor,
                            PixelFormats.Default);
                        bmp.Render(fe);
                        PngBitmapEncoder png = new PngBitmapEncoder();
                        png.Frames.Add(BitmapFrame.Create(bmp));
                        using (Stream stream = File.Create(outputPath))
                        {
                            png.Save(stream);
                        }
                    }

                    System.Windows.MessageBox.Show("Images Saved Successfully", "Status", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    System.Windows.MessageBox.Show("Please select a office File (*.docx,*.doc,*.els,*.elsx,*.ppt,*.pptx)", "Select a MS Office File", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception)
            {
                System.Windows.MessageBox.Show("Please Select a Folder Loaction to Store the Images", "Select a Folder Loaction", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
예제 #2
0
 public WelcomeWindow()
 {
     InitializeComponent();
     Owner = Application.Current.MainWindow;
     System.Windows.Xps.Packaging.XpsDocument d = new System.Windows.Xps.Packaging.XpsDocument(".\\Welcome.xps", FileAccess.Read);
     rd.Document = d.GetFixedDocumentSequence();
 }
예제 #3
0
        static public void SaveXpsPageToBitmap(string xpsFileName)
        {
            System.Windows.Xps.Packaging.XpsDocument       xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFileName, FileAccess.Read);
            System.Windows.Documents.FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();

            // You can get the total page count from docSeq.PageCount
            for (int pageNum = 0; pageNum < docSeq.DocumentPaginator.PageCount; ++pageNum)
            {
                DocumentPage       docPage      = docSeq.DocumentPaginator.GetPage(pageNum);
                RenderTargetBitmap renderTarget =
                    new RenderTargetBitmap((int)docPage.Size.Width,
                                           (int)docPage.Size.Height,
                                           96, // WPF (Avalon) units are 96dpi based
                                           96,
                                           PixelFormats.Default);

                renderTarget.Render(docPage.Visual);

                BitmapEncoder encoder = new BmpBitmapEncoder(); // Choose type here ie: JpegBitmapEncoder, etc
                encoder.Frames.Add(BitmapFrame.Create(renderTarget));

                FileStream pageOutStream = new FileStream(xpsFileName + ".Page" + pageNum + ".bmp", FileMode.Create, FileAccess.Write);
                encoder.Save(pageOutStream);
                pageOutStream.Close();
            }
        }
 public void ListViewScannedFiles_SelectionChanged(object sender, RoutedEventArgs args)
 {
     if (this.listViewScannedFiles.SelectedItem != null)
     {
         System.Windows.Xps.Packaging.XpsDocument xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(@"c:\ypiidata\xpsdocument55.xps", System.IO.FileAccess.Read);
         this.DocumentViewer.Document = xpsDocument.GetFixedDocumentSequence();
     }
 }
예제 #5
0
        public override void ShowHelp(bool asDialog)
        {
            var helpUri  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Resources.HelpFile);
            var document = new System.Windows.Xps.Packaging.XpsDocument(helpUri, FileAccess.Read);

            var helpWindow = new Window
            {
                Icon        = Application.Current.MainWindow.Icon,
                Title       = CommonSettings.AppName + ": " + Resources.XpsHelp,
                WindowState = WindowState.Maximized
            };

            var docViewer = new System.Windows.Controls.DocumentViewer {
                Document = document.GetFixedDocumentSequence()
            };
            var frame = new System.Windows.Controls.Frame {
                NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Hidden
            };

            frame.Content      = docViewer;
            helpWindow.Content = frame;

            helpWindow.Closed += (sender, e) =>
            {
                document.Close();
            };

            docViewer.AddHandler(System.Windows.Documents.Hyperlink.RequestNavigateEvent,
                                 new System.Windows.Navigation.RequestNavigateEventHandler((sender, e) =>
            {
                if (e.Uri.IsAbsoluteUri && e.Uri.Scheme == "http")
                {
                    try
                    {
                        Process.Start(e.Uri.ToString());
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show(string.Format(Resources.SiteNavigationError + "\r\n{1}", e.Uri, exc.Message), CommonSettings.AppName);
                    }

                    e.Handled = true;
                }
            }
                                                                                           ));

            if (asDialog)
            {
                helpWindow.ShowDialog();
            }
            else
            {
                helpWindow.Show();
            }
        }
예제 #6
0
        private void OpenSourceFile_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            string xpsFilePath = String.Empty;

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".txt";
            dlg.Filter     = "Office Files(*.docx;*.doc;*.xlsx;*.xls;*.pptx;*.ppt)|*.docx;*.doc;*.xlsx;*.xls;*.pptx;*.ppt";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable <bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                string filename = dlg.FileName;
                xpsFilePath    = System.Environment.CurrentDirectory + "\\" + dlg.SafeFileName + ".xps";
                SourceUrl.Text = filename;
            }

            var convertResults = OfficeToXps.ConvertToXps(SourceUrl.Text, ref xpsFilePath);

            switch (convertResults.Result)
            {
            case ConversionResult.OK:
                xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFilePath, FileAccess.ReadWrite);
                documentViewer1.Document = xpsDoc.GetFixedDocumentSequence();
                officeFileOpen_Status    = true;
                break;

            case ConversionResult.InvalidFilePath:
                // Handle bad file path or file missing
                break;

            case ConversionResult.UnexpectedError:
                // This should only happen if the code is modified poorly
                break;

            case ConversionResult.ErrorUnableToInitializeOfficeApp:
                // Handle Office 2007 (Word | Excel | PowerPoint) not installed
                break;

            case ConversionResult.ErrorUnableToOpenOfficeFile:
                // Handle source file being locked or invalid permissions
                break;

            case ConversionResult.ErrorUnableToAccessOfficeInterop:
                // Handle Office 2007 (Word | Excel | PowerPoint) not installed
                break;

            case ConversionResult.ErrorUnableToExportToXps:
                // Handle Microsoft Save As PDF or XPS Add-In missing for 2007
                break;
            }
        }
예제 #7
0
    static void convert(double dpi, string path, string out_path)
    {
        double scale = dpi / 96.0;

        System.Windows.Xps.Packaging.XpsDocument xpsDoc =
            new System.Windows.Xps.Packaging.XpsDocument(
                path, System.IO.FileAccess.Read);
        if (xpsDoc == null)
        {
            throw new System.Exception("XpsDocumentfailed");
        }
        System.Windows.Documents.FixedDocumentSequence docSeq =
            xpsDoc.GetFixedDocumentSequence();
        if (docSeq == null)
        {
            throw new System.Exception("GetFixedDocumentSequence failed");
        }
        System.Windows.Documents.DocumentReferenceCollection drc = docSeq.References;
        int index = 0;

        foreach (System.Windows.Documents.DocumentReference dr in drc)
        {
            System.Windows.Documents.FixedDocument dp = dr.GetDocument(false);
            foreach (System.Windows.Documents.PageContent pc in dp.Pages)
            {
                System.Windows.Documents.FixedPage fixedPage = pc.GetPageRoot(false);
                double width           = fixedPage.Width;
                double height          = fixedPage.Height;
                System.Windows.Size sz = new System.Windows.Size(width, height);
                fixedPage.Measure(sz);
                fixedPage.Arrange(
                    new System.Windows.Rect(new System.Windows.Point(), sz));
                fixedPage.UpdateLayout();
                System.Windows.Media.Imaging.BitmapImage bitmap =
                    new System.Windows.Media.Imaging.BitmapImage();
                System.Windows.Media.Imaging.RenderTargetBitmap renderTarget =
                    new System.Windows.Media.Imaging.RenderTargetBitmap(
                        ceil(scale * width), ceil(scale * height), dpi, dpi,
                        System.Windows.Media.PixelFormats.Default);
                renderTarget.Render(fixedPage);
                System.Windows.Media.Imaging.BitmapEncoder encoder =
                    new System.Windows.Media.Imaging.PngBitmapEncoder();
                encoder.Frames.Add(
                    System.Windows.Media.Imaging.BitmapFrame.Create(renderTarget));
                string filename = string.Format("{0}_{1}.png", out_path, index);
                System.IO.FileStream pageOutStream = new System.IO.FileStream(
                    filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                encoder.Save(pageOutStream);
                pageOutStream.Close();
                System.Console.WriteLine(filename);
                ++index;
            }
        }
    }
예제 #8
0
파일: xps_to_png.cs 프로젝트: aseprite/skia
 static void convert(double dpi, string path, string out_path)
 {
     double scale = dpi / 96.0;
     System.Windows.Xps.Packaging.XpsDocument xpsDoc =
             new System.Windows.Xps.Packaging.XpsDocument(
                     path, System.IO.FileAccess.Read);
     if (xpsDoc == null) {
         throw new System.Exception("XpsDocumentfailed");
     }
     System.Windows.Documents.FixedDocumentSequence docSeq =
             xpsDoc.GetFixedDocumentSequence();
     if (docSeq == null) {
         throw new System.Exception("GetFixedDocumentSequence failed");
     }
     System.Windows.Documents.DocumentReferenceCollection drc = docSeq.References;
     int index = 0;
     foreach (System.Windows.Documents.DocumentReference dr in drc) {
         System.Windows.Documents.FixedDocument dp = dr.GetDocument(false);
         foreach (System.Windows.Documents.PageContent pc in dp.Pages) {
             System.Windows.Documents.FixedPage fixedPage = pc.GetPageRoot(false);
             double width = fixedPage.Width;
             double height = fixedPage.Height;
             System.Windows.Size sz = new System.Windows.Size(width, height);
             fixedPage.Measure(sz);
             fixedPage.Arrange(
                     new System.Windows.Rect(new System.Windows.Point(), sz));
             fixedPage.UpdateLayout();
             System.Windows.Media.Imaging.BitmapImage bitmap =
                     new System.Windows.Media.Imaging.BitmapImage();
             System.Windows.Media.Imaging.RenderTargetBitmap renderTarget =
                     new System.Windows.Media.Imaging.RenderTargetBitmap(
                         ceil(scale * width), ceil(scale * height), dpi, dpi,
                         System.Windows.Media.PixelFormats.Default);
             renderTarget.Render(fixedPage);
             System.Windows.Media.Imaging.BitmapEncoder encoder =
                 new System.Windows.Media.Imaging.PngBitmapEncoder();
             encoder.Frames.Add(
                     System.Windows.Media.Imaging.BitmapFrame.Create(renderTarget));
             string filename = string.Format("{0}_{1}.png", out_path, index);
             System.IO.FileStream pageOutStream = new System.IO.FileStream(
                 filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
             encoder.Save(pageOutStream);
             pageOutStream.Close();
             System.Console.WriteLine(filename);
             ++index;
         }
     }
 }
예제 #9
0
        private void Preview(bool write)
        {
            var progressDialog = new ProgressDialog(false);

            progressDialog.Show();
            Previewer.Document = null;
            try
            {
                Task.Run(() =>
                {
                    var xpsFilePath   = Environment.CurrentDirectory + $"\\{OfficeToXps.TempNum++}.xps";
                    var excelFilePath = (Properties.Settings.Default.TamplatePath == "") ?
                                        Environment.CurrentDirectory + "\\库存模板.xlsx" : Properties.Settings.Default.TamplatePath;
                    var tempFilePath = Environment.CurrentDirectory + "\\temp.xlsx";
                    File.Copy(excelFilePath, Environment.CurrentDirectory + "\\temp.xlsx", true);
                    if (write)
                    {
                        WriteWarehouseToExcel(tempFilePath);
                    }
                    var convertResults = OfficeToXps.ConvertToXps(tempFilePath, ref xpsFilePath);
                    switch (convertResults.Result)
                    {
                    case ConversionResult.OK:
                        xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFilePath, FileAccess.ReadWrite);
                        Dispatcher.Invoke(() =>
                        {
                            Previewer.Document = xpsDoc.GetFixedDocumentSequence();
                        });

                        break;

                    default:
                        throw new Exception();
                    }
                });
            }
            catch
            {
                new InfoDialog("请安装Microsoft Office!", false).Show();
            }
            finally
            {
                progressDialog.Close();
            }
        }
예제 #10
0
        public CHelpBox(bool leftSide, string title, string message, int page)
        {
            InitializeComponent();
            this.LabelTitle.Content     = title;
            this.TextBlock_Message.Text = message;
            //string imageBig = "pack://*****:*****@"C:\Users\rsche\Desktop\Cpu1802.xps";

            string resPath  = System.IO.Path.GetFullPath("Resources");
            string fileName = resPath + "\\Cpu1802.xps";

            System.Windows.Xps.Packaging.XpsDocument doc = new System.Windows.Xps.Packaging.XpsDocument(fileName, FileAccess.Read);
            this.DocumentViewerHelp.Document = doc.GetFixedDocumentSequence();


            this.DocumentViewerHelp.GoToPage(page);
        }
예제 #11
0
    static public void SaveXpsPageToBitmap(string xpsFileName)
    {
      System.Windows.Xps.Packaging.XpsDocument xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFileName, System.IO.FileAccess.Read);
      System.Windows.Documents.FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();

      // You can get the total page count from docSeq.PageCount    
      for (int pageNum = 0; pageNum < docSeq.DocumentPaginator.PageCount; ++pageNum)
      {
        DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageNum);
        RenderTargetBitmap renderTarget =
            new RenderTargetBitmap((int)docPage.Size.Width,
                                    (int)docPage.Size.Height,
                                    96, // WPF (Avalon) units are 96dpi based    
                                    96,
                                    System.Windows.Media.PixelFormats.Default);

        renderTarget.Render(docPage.Visual);

        BitmapEncoder encoder = new BmpBitmapEncoder();  // Choose type here ie: JpegBitmapEncoder, etc   
        encoder.Frames.Add(BitmapFrame.Create(renderTarget));

        FileStream pageOutStream = new FileStream(xpsFileName + ".Page" + pageNum + ".bmp", FileMode.Create, FileAccess.Write);
        encoder.Save(pageOutStream);
        pageOutStream.Close();
      }
    }
예제 #12
0
        /// <summary>
        /// Implements the PDF file to XPS file conversion.
        /// </summary>
        public static void Convert(string xpsFilename, string pdfFilename, int docIndex, bool createComparisonDocument)
        {
            if (String.IsNullOrEmpty(xpsFilename))
            {
                throw new ArgumentNullException("xpsFilename");
            }

            if (String.IsNullOrEmpty(pdfFilename))
            {
                pdfFilename = xpsFilename;
                if (IOPath.HasExtension(pdfFilename))
                {
                    pdfFilename = pdfFilename.Substring(0, pdfFilename.LastIndexOf('.'));
                }
                pdfFilename += ".pdf";
            }

            XpsDocument xpsDocument = null;

            try
            {
                xpsDocument = XpsDocument.Open(xpsFilename);
                FixedDocument fixedDocument = xpsDocument.GetDocument();
                PdfDocument   pdfDocument   = new PdfDocument();
                PdfRenderer   renderer      = new PdfRenderer();

                int pageIndex = 0;
                foreach (FixedPage page in fixedDocument.Pages)
                {
                    if (page == null)
                    {
                        continue;
                    }
                    Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));
                    PdfPage pdfPage = renderer.CreatePage(pdfDocument, page);
                    renderer.RenderPage(pdfPage, page);
                    pageIndex++;

#if DEBUG
                    // stop at page...
                    if (pageIndex == 50)
                    {
                        break;
                    }
#endif
                }
                pdfDocument.Save(pdfFilename);
                xpsDocument.Close();
                xpsDocument = null;

                if (createComparisonDocument)
                {
                    System.Windows.Xps.Packaging.XpsDocument       xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFilename, FileAccess.Read);
                    System.Windows.Documents.FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();
                    if (docSeq == null)
                    {
                        throw new InvalidOperationException("docSeq");
                    }

                    XPdfForm    form = XPdfForm.FromFile(pdfFilename);
                    PdfDocument pdfComparisonDocument = new PdfDocument();


                    pageIndex = 0;
                    foreach (PdfPage page in pdfDocument.Pages)
                    {
                        if (page == null)
                        {
                            continue;
                        }
                        Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));

                        PdfPage pdfPage = /*renderer.CreatePage(pdfComparisonDocument, page);*/ pdfComparisonDocument.AddPage();
                        double  width   = page.Width;
                        double  height  = page.Height;
                        pdfPage.Width  = page.Width * 2;
                        pdfPage.Height = page.Height;


                        DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageIndex);
                        //byte[] png = PngFromPage(docPage, 96);

                        BitmapSource bmsource = BitmapSourceFromPage(docPage, 96 * 2);
                        XImage       image    = XImage.FromBitmapSource(bmsource);

                        XGraphics gfx = XGraphics.FromPdfPage(pdfPage);
                        form.PageIndex = pageIndex;
                        gfx.DrawImage(form, 0, 0, width, height);
                        gfx.DrawImage(image, width, 0, width, height);

                        //renderer.RenderPage(pdfPage, page);
                        pageIndex++;

#if DEBUG
                        // stop at page...
                        if (pageIndex == 50)
                        {
                            break;
                        }
#endif
                    }

                    string pdfComparisonFilename = pdfFilename;
                    if (IOPath.HasExtension(pdfComparisonFilename))
                    {
                        pdfComparisonFilename = pdfComparisonFilename.Substring(0, pdfComparisonFilename.LastIndexOf('.'));
                    }
                    pdfComparisonFilename += "-comparison.pdf";

                    pdfComparisonDocument.ViewerPreferences.FitWindow = true;
                    //pdfComparisonDocument.PageMode = PdfPageMode.
                    pdfComparisonDocument.PageLayout = PdfPageLayout.SinglePage;
                    pdfComparisonDocument.Save(pdfComparisonFilename);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                if (xpsDocument != null)
                {
                    xpsDocument.Close();
                }
                throw;
            }
            finally
            {
                if (xpsDocument != null)
                {
                    xpsDocument.Close();
                }
            }
        }
 public void ListViewScannedFiles_SelectionChanged(object sender, RoutedEventArgs args)
 {
     if (this.listViewScannedFiles.SelectedItem != null)
     {
         System.Windows.Xps.Packaging.XpsDocument xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(@"c:\ypiidata\xpsdocument55.xps", System.IO.FileAccess.Read);
         this.DocumentViewer.Document = xpsDocument.GetFixedDocumentSequence();
     }
 }
예제 #14
0
 //文档装载预览
 void UC_PrintPreview_Loaded(object sender, RoutedEventArgs e)
 {
     dvcontent.Zoom = 75.0;
     try
     {
         if (!string.IsNullOrWhiteSpace(GlobalCodeBuilder.filePaht))
         {
             string[] strArr = GlobalCodeBuilder.filePaht.Split('\\');
             string xpsName = strArr[strArr.Length - 1].Substring(0, strArr[strArr.Length - 1].IndexOf('.'));
             string xpsfilename = AppDomain.CurrentDomain.BaseDirectory + string.Format(@"Docs\{0}.xps", xpsName);
             string err = "";
             doc = FileHelper.ConvertWordToXps(GlobalCodeBuilder.filePaht, xpsfilename, out err);
             if (!string.IsNullOrWhiteSpace(err))
             {
                 MessageBox.Show("doc is err:" +err);
             }
             if (doc != null)
             {
                 dvcontent.Visibility = Visibility.Visible;
                 dvcontent.Document = doc.GetFixedDocumentSequence();
                 doc.Close();
             }
         }
         else {
             MessageBox.Show("未能正确获取文档地址");
             BackHoem();
         }
     }
     catch (Exception ex)
     {
         HttpAPIService.LiveReportAPI(HttpUtility.UrlEncode("文档预览错误"),"0");
         BackHoem();
     }
 }
예제 #15
0
        protected MatrixBase()
        {
            this.CommandCopyToClipboard = new DelegateCommand(
                this.CopyToClipboard,
                () =>
            {
                return(this.HasData);
            });

            this.CommandPrint = new DelegateCommand(
                () =>
            {
                var section           = Helpers.FormatHelper.MatrixToFlowDocumentSectionWithTable(this);
                var flowDocument      = new System.Windows.Documents.FlowDocument(section);
                flowDocument.FontSize = 11d;

                System.Windows.Controls.PrintDialog pd = new System.Windows.Controls.PrintDialog();
                System.Printing.PrintTicket pt         = new System.Printing.PrintTicket();
                pt.PageOrientation = System.Printing.PageOrientation.Landscape;
                pd.PrintTicket     = pd.PrintQueue.MergeAndValidatePrintTicket(pd.PrintQueue.DefaultPrintTicket, pt).ValidatedPrintTicket;

                System.Windows.Documents.IDocumentPaginatorSource fdd = flowDocument;
                flowDocument.PageWidth   = pd.PrintableAreaWidth;
                flowDocument.PageHeight  = pd.PrintableAreaHeight;
                flowDocument.ColumnWidth = pd.PrintableAreaWidth;
                flowDocument.PagePadding = new Thickness(30.0, 50.0, 20.0, 30.0);
                flowDocument.IsOptimalParagraphEnabled = true;
                flowDocument.IsHyphenationEnabled      = true;

                var ms = new System.IO.MemoryStream();
                using (var pkg = System.IO.Packaging.Package.Open(ms, System.IO.FileMode.Create))
                {
                    using (System.Windows.Xps.Packaging.XpsDocument doc = new System.Windows.Xps.Packaging.XpsDocument(pkg))
                    {
                        System.Windows.Xps.XpsDocumentWriter writer = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(doc);
                        writer.Write(fdd.DocumentPaginator);
                    }
                }

                ms.Position = 0;
                var pkg2    = System.IO.Packaging.Package.Open(ms);

                // Read the XPS document into a dynamically generated
                // preview Window
                var url = new Uri("memorystream://printstream");
                System.IO.Packaging.PackageStore.AddPackage(url, pkg2);
                try
                {
                    using (System.Windows.Xps.Packaging.XpsDocument doc = new System.Windows.Xps.Packaging.XpsDocument(pkg2, System.IO.Packaging.CompressionOption.SuperFast, url.AbsoluteUri))
                    {
                        System.Windows.Documents.FixedDocumentSequence fds = doc.GetFixedDocumentSequence();

                        Window wnd = new Window();
                        wnd.Title  = string.Format("Предварительный просмотр :: {0}", this.Header);
                        wnd.Owner  = Application.Current.MainWindow;
                        System.Windows.Media.TextOptions.SetTextFormattingMode(wnd, System.Windows.Media.TextFormattingMode.Display);
                        wnd.Padding = new Thickness(2);
                        wnd.Content = new System.Windows.Controls.DocumentViewer()
                        {
                            Document = fds,
                        };
                        wnd.ShowDialog();
                    }
                }
                finally
                {
                    System.IO.Packaging.PackageStore.RemovePackage(url);
                }
            },
                () =>
            {
                return(this.HasData);
            });

            this.CommandRefresh = new DelegateCommand(this.Build, () => this.HasData);
        }
예제 #16
-1
    /// <summary>
    /// Implements the PDF file to XPS file conversion.
    /// </summary>
    public static void Convert(string xpsFilename, string pdfFilename, int docIndex, bool createComparisonDocument)
    {
      if (String.IsNullOrEmpty(xpsFilename))
        throw new ArgumentNullException("xpsFilename");

      if (String.IsNullOrEmpty(pdfFilename))
      {
        pdfFilename = xpsFilename;
        if (IOPath.HasExtension(pdfFilename))
          pdfFilename = pdfFilename.Substring(0, pdfFilename.LastIndexOf('.'));
        pdfFilename += ".pdf";
      }

      XpsDocument xpsDocument = null;
      try
      {
        xpsDocument = XpsDocument.Open(xpsFilename);
        FixedDocument fixedDocument = xpsDocument.GetDocument();
        PdfDocument pdfDocument = new PdfDocument();
        PdfRenderer renderer = new PdfRenderer();

        int pageIndex = 0;
        foreach (FixedPage page in fixedDocument.Pages)
        {
          if (page == null)
            continue;
          Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));
          PdfPage pdfPage = renderer.CreatePage(pdfDocument, page);
          renderer.RenderPage(pdfPage, page);
          pageIndex++;

#if DEBUG
          // stop at page...
          if (pageIndex == 50)
            break;
#endif
        }
        pdfDocument.Save(pdfFilename);
        xpsDocument.Close();
        xpsDocument = null;

        if (createComparisonDocument)
        {
          System.Windows.Xps.Packaging.XpsDocument xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFilename, FileAccess.Read);
          System.Windows.Documents.FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence();
          if (docSeq == null)
            throw new InvalidOperationException("docSeq");

          XPdfForm form = XPdfForm.FromFile(pdfFilename);
          PdfDocument pdfComparisonDocument = new PdfDocument();


          pageIndex = 0;
          foreach (PdfPage page in pdfDocument.Pages)
          {
            if (page == null)
              continue;
            Debug.WriteLine(String.Format("  doc={0}, page={1}", docIndex, pageIndex));

            PdfPage pdfPage = /*renderer.CreatePage(pdfComparisonDocument, page);*/pdfComparisonDocument.AddPage();
            double width = page.Width;
            double height = page.Height;
            pdfPage.Width = page.Width * 2;
            pdfPage.Height = page.Height;


            DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageIndex);
            //byte[] png = PngFromPage(docPage, 96);

            BitmapSource bmsource = BitmapSourceFromPage(docPage, 96 * 2);
            XImage image = XImage.FromBitmapSource(bmsource);

            XGraphics gfx = XGraphics.FromPdfPage(pdfPage);
            form.PageIndex = pageIndex;
            gfx.DrawImage(form, 0, 0, width, height);
            gfx.DrawImage(image, width, 0, width, height);

            //renderer.RenderPage(pdfPage, page);
            pageIndex++;

#if DEBUG
            // stop at page...
            if (pageIndex == 50)
              break;
#endif
          }

          string pdfComparisonFilename = pdfFilename;
          if (IOPath.HasExtension(pdfComparisonFilename))
            pdfComparisonFilename = pdfComparisonFilename.Substring(0, pdfComparisonFilename.LastIndexOf('.'));
          pdfComparisonFilename += "-comparison.pdf";

          pdfComparisonDocument.ViewerPreferences.FitWindow = true;
          //pdfComparisonDocument.PageMode = PdfPageMode.
          pdfComparisonDocument.PageLayout = PdfPageLayout.SinglePage;
          pdfComparisonDocument.Save(pdfComparisonFilename);
        }

      }
      catch (Exception ex)
      {
        Debug.WriteLine(ex.Message);
        if (xpsDocument != null)
          xpsDocument.Close();
        throw;
      }
      finally
      {
        if (xpsDocument != null)
          xpsDocument.Close();
      }
    }