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 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(); }
public static void SaveToPdf(UIElement ui, string name) { //MigraDoc.DocumentObjectModel.Document doc = new MigraDoc.DocumentObjectModel.Document(); //MigraDoc.Rendering.DocumentRenderer renderer = new DocumentRenderer(doc); //MigraDoc.Rendering.PdfDocumentRenderer pdfRenderer = new MigraDoc.Rendering.PdfDocumentRenderer(); //pdfRenderer.PdfDocument = pDoc; //pdfRenderer.DocumentRenderer = renderer; //using (MemoryStream ms = new MemoryStream()) //{ // pdfRenderer.Save(ms, false); // byte[] buffer = new byte[ms.Length]; // ms.Seek(0, SeekOrigin.Begin); // ms.Flush(); // ms.Read(buffer, 0, (int)ms.Length); //} string path = string.Format(name + "_{0}.pdf", DateTime.Now.ToString("MMddyyyy_hhmmss")); FileOperations.EnsureFileFolderExist(path); MemoryStream lMemoryStream = new MemoryStream(); Package package = Package.Open(lMemoryStream, FileMode.Create); System.Windows.Xps.Packaging.XpsDocument doc = new System.Windows.Xps.Packaging.XpsDocument(package); System.Windows.Xps.XpsDocumentWriter writer = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(doc); writer.Write(ui); doc.Close(); package.Close(); PdfSharp.Xps.XpsModel.XpsDocument pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream); PdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, path, 0); }
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(); } }
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(); } }
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; } }
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; } } }
private void DestinationLoaction_Click(object sender, RoutedEventArgs e) { if (officeFileOpen_Status) { FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog(); DialogResult result = folderBrowserDialog1.ShowDialog(); string localpath = String.Empty; localpath = folderBrowserDialog1.SelectedPath + "\\OutputXpsDocument.xps"; var convertResults = OfficeToXps.ConvertToXps(SourceUrl.Text, ref localpath); switch (convertResults.Result) { case ConversionResult.OK: System.Windows.Xps.Packaging.XpsDocument xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(localpath, FileAccess.ReadWrite); break; case ConversionResult.InvalidFilePath: System.Windows.MessageBox.Show("Files Missing in the mentioned Path", "InValid Path", MessageBoxButton.OK, MessageBoxImage.Information); break; case ConversionResult.UnexpectedError: // This should only happen if the code is modified poorly break; case ConversionResult.ErrorUnableToInitializeOfficeApp: System.Windows.MessageBox.Show("Microsoft Office not Installed in the Machine", "Software Incompatibility", MessageBoxButton.OK, MessageBoxImage.Information); break; case ConversionResult.ErrorUnableToOpenOfficeFile: // Handle source file being locked or invalid permissions break; case ConversionResult.ErrorUnableToAccessOfficeInterop: System.Windows.MessageBox.Show("Microsoft Office not Installed in the Machine", "Software Incompatibility", MessageBoxButton.OK, MessageBoxImage.Information); break; case ConversionResult.ErrorUnableToExportToXps: // Handle Microsoft Save As PDF or XPS Add-In missing for 2007 break; } System.Windows.MessageBox.Show("File 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); } }
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(); } }
private const double DPCM = 96 / 2.54; //1cm中的像素点数量 /// <summary> /// 保存到XPS格式文档 /// </summary> /// <param name="xpsFilename">XPS文件名</param> /// <param name="fixedDoc">XPS文档</param> public static bool SaveToXpsFile(string xpsFilename, FixedDocument fixedDoc) { try { //保存到XPS文件 DocumentPaginator paginator = fixedDoc.DocumentPaginator; System.Windows.Xps.Packaging.XpsDocument xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(xpsFilename, System.IO.FileAccess.Write); var documentWriter = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(xpsDocument); documentWriter.Write(paginator); xpsDocument.Close(); return(true); } catch (Exception ex) { ErrorString = ex.Message; return(false); } }
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); }
/// <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(); } } }
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(); } }
/// <summary> /// Convert the word document to xps document /// </summary> /// <param name="wordFilename">Word document Path</param> /// <param name="xpsFilename">Xps document Path</param> /// <returns></returns> public static System.Windows.Xps.Packaging.XpsDocument ConvertWordToXPS(string wordDocName, string xpsDocName, out string err) { err = ""; System.Windows.Xps.Packaging.XpsDocument result = null; //创建一个word文档,并将要转换的文档添加到新创建的对象 Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application(); try { wordApplication.Documents.Add(wordDocName); Microsoft.Office.Interop.Word.Document doc = wordApplication.ActiveDocument; doc.ExportAsFixedFormat(xpsDocName, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatXPS, false, Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 0, 0, Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent, true, true, Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateHeadingBookmarks, true, true, false, Type.Missing); result = new System.Windows.Xps.Packaging.XpsDocument(xpsDocName, System.IO.FileAccess.ReadWrite); } catch (Exception ex) { err = "wordDocName:" + wordDocName + ",xpsDocName:" + xpsDocName+",err:"+ex.Message; wordApplication.Quit(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges); } wordApplication.Quit(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges); return result; }
//完成打印 private void FinishPrint() { var printers = new LocalPrintServer().GetPrintQueues(); var selectedPrinter = printers.FirstOrDefault(p => p.Name == Global.A4PrinterName); var wpfPrint = new PrintDialog(); wpfPrint.PrintQueue = selectedPrinter; var pt = new PrintTicket(); pt.PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4); //设置文档打印尺寸 wpfPrint.PrintTicket = pt; if (doc == null) { 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}-temp.xps", xpsName); string err = ""; doc = FileHelper.ConvertWordToXps(GlobalCodeBuilder.filePaht, xpsfilename, out err); if (!string.IsNullOrWhiteSpace(err)) { MessageBox.Show("doc is err:" + err); } } else { MessageBox.Show("未能正确获取文档地址"); BackHoem(); } } wpfPrint.PrintDocument(doc.GetFixedDocumentSequence().DocumentPaginator, "云文档打印"); if (doc != null) { dvcontent.Visibility = Visibility.Visible; dvcontent.Document = doc.GetFixedDocumentSequence(); doc.Close(); } Thread.Sleep(1000); if (!string.IsNullOrWhiteSpace(GlobalCodeBuilder.filePaht)) { FileHelper.DeleteFile(GlobalCodeBuilder.filePaht); string xpsFile = GlobalCodeBuilder.filePaht.Substring(0, GlobalCodeBuilder.filePaht.LastIndexOf('.')) + ".xps"; FileHelper.DeleteFile(xpsFile); string xpsTempFile = GlobalCodeBuilder.filePaht.Substring(0, GlobalCodeBuilder.filePaht.LastIndexOf('.')) + "-temp.xps"; FileHelper.DeleteFile(xpsTempFile); } GlobalCodeBuilder.filePaht = ""; new Thread(() => { this.Dispatcher.Invoke(new Action(() => { imgViewPrintFinish.Visibility = Visibility.Visible; imgViewPrting.Visibility = Visibility.Collapsed; GlobalCodeBuilder.ProcessNum += 1; ProcessInit(); GlobalCodeBuilder.ProcessNum = 1; //子线程打印 Thread printThread = new Thread(GoBackMain); printThread.IsBackground = true; printThread.Start(); })); }).Start(); }
private Public.ImageStream RenderXps() { Public.ImageStream renderedImage = new Public.ImageStream(); System.IO.MemoryStream renderedContent = new System.IO.MemoryStream(); String contentUriName = ("memorystream://rendered" + Guid.NewGuid().ToString().Replace("-", "") + ".xps"); Uri contentUri = new Uri(contentUriName, UriKind.Absolute); // FOR TESTING, OUTPUT TO DISK FILE BY CHANGING OPEN FROM MEMORY STREAM TO FILE LOCATION System.IO.Packaging.Package xpsPackage = System.IO.Packaging.Package.Open(renderedContent, System.IO.FileMode.Create); System.IO.Packaging.PackageStore.AddPackage(contentUri, xpsPackage); System.Windows.Xps.Packaging.XpsDocument renderedXpsDocument = new System.Windows.Xps.Packaging.XpsDocument(xpsPackage, System.IO.Packaging.CompressionOption.Normal, contentUriName); System.Windows.Xps.XpsDocumentWriter xpsWriter = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(renderedXpsDocument); System.Windows.Xps.Packaging.IXpsFixedDocumentSequenceWriter contentSequenceWriter; contentSequenceWriter = renderedXpsDocument.AddFixedDocumentSequence(); List <System.Windows.Xps.Packaging.XpsDocument> xpsContents = new List <System.Windows.Xps.Packaging.XpsDocument> (); // LOAD CORRESPONDENCE RECORD TO SEE IF THERE IS ANY CONTENT AVAILABLE Reference.Correspondence renderCorrespondence = application.CorrespondenceGet(correspondenceId); if (renderCorrespondence == null) { throw new ApplicationException("Unable to load base Correspondence to Render Content."); } if (renderCorrespondence.Content.Count == 0) { throw new ApplicationException("No Content to Render for Correspondence."); } renderCorrespondence.LoadContentAttachments(); foreach (Reference.CorrespondenceContent currentCorrespondenceContent in renderCorrespondence.Content.Values) { System.Windows.Xps.Packaging.XpsDocument xpsContent = null; switch (currentCorrespondenceContent.ContentType) { case Reference.Enumerations.CorrespondenceContentType.Report: #region Generate Report Content Reporting.ReportingServer reportingServer = application.ReportingServerGet(currentCorrespondenceContent.ReportingServerId); if (reportingServer == null) { throw new ApplicationException("Unable to load Reporting Server to Render Content."); } System.Reflection.Assembly reportingServerAssembly = System.Reflection.Assembly.LoadFrom(reportingServer.AssemblyReference); Type reportingServerType = reportingServerAssembly.GetType(reportingServer.AssemblyClassName); if (reportingServerType == null) { throw new ApplicationException("Unable to find Class [" + reportingServer.AssemblyClassName + "] in referenced Assembly [" + reportingServer.AssemblyReference + "]."); } Public.Reporting.IReportingServer reportingServerObject = (Public.Reporting.IReportingServer)Activator.CreateInstance(reportingServerType); Dictionary <String, String> reportParameters = new Dictionary <String, String> (); reportParameters.Add("entityCorrespondenceId", id.ToString()); // SSRS RENDER TIFF, CONVERT TO XPS Public.ImageStream imageStream = reportingServerObject.Render(reportingServer.WebServiceHostConfiguration, currentCorrespondenceContent.ReportName, reportParameters, "image", reportingServer.ExtendedProperties); xpsContent = imageStream.TiffToXps(); xpsContents.Add(xpsContent); #endregion break; case Reference.Enumerations.CorrespondenceContentType.Attachment: #region Load Attachment contentUriName = ("memorystream://attachment" + Guid.NewGuid().ToString().Replace("-", "") + ".xps"); contentUri = new Uri(contentUriName, UriKind.Absolute); System.IO.MemoryStream attachmentStream = new System.IO.MemoryStream(); System.IO.Packaging.Package attachmentPackage = System.IO.Packaging.Package.Open(currentCorrespondenceContent.Attachment); System.IO.Packaging.PackageStore.AddPackage(contentUri, attachmentPackage); xpsContent = new System.Windows.Xps.Packaging.XpsDocument(attachmentPackage, System.IO.Packaging.CompressionOption.Normal, contentUriName); xpsContents.Add(xpsContent); #endregion break; } } #region Merge XPS Contents foreach (System.Windows.Xps.Packaging.XpsDocument currentContentDocument in xpsContents) { foreach (System.Windows.Xps.Packaging.IXpsFixedDocumentReader currentContentDocumentReader in currentContentDocument.FixedDocumentSequenceReader.FixedDocuments) { System.Windows.Xps.Packaging.IXpsFixedDocumentWriter contentDocumentWriter = contentSequenceWriter.AddFixedDocument(); foreach (System.Windows.Xps.Packaging.IXpsFixedPageReader currentContentPageReader in currentContentDocumentReader.FixedPages) { System.Windows.Xps.Packaging.IXpsFixedPageWriter contentPageWriter = contentDocumentWriter.AddFixedPage(); System.Xml.XmlWriter xmlPageWriter = contentPageWriter.XmlWriter; String pageContent = CommonFunctions.XmlReaderToString(currentContentPageReader.XmlReader); #region Resource Dictionaries foreach (System.Windows.Xps.Packaging.XpsResourceDictionary currentXpsDictionary in currentContentPageReader.ResourceDictionaries) { System.Windows.Xps.Packaging.XpsResourceDictionary xpsDictionary = contentPageWriter.AddResourceDictionary(); System.IO.Stream xpsDictionaryStream = xpsDictionary.GetStream(); // GET DESTINATION STREAM TO COPY TO currentXpsDictionary.GetStream().CopyTo(xpsDictionaryStream); // REMAP SOURCE URI pageContent = pageContent.Replace(currentXpsDictionary.Uri.ToString(), xpsDictionary.Uri.ToString()); xpsDictionary.Commit(); } #endregion #region Color Contexts foreach (System.Windows.Xps.Packaging.XpsColorContext currentXpsColorContext in currentContentPageReader.ColorContexts) { System.Windows.Xps.Packaging.XpsColorContext xpsColorContext = contentPageWriter.AddColorContext(); System.IO.Stream xpsColorContextStream = xpsColorContext.GetStream(); // GET DESTINATION STREAM TO COPY TO currentXpsColorContext.GetStream().CopyTo(xpsColorContextStream); // REMAP SOURCE URI pageContent = pageContent.Replace(currentXpsColorContext.Uri.ToString(), xpsColorContext.Uri.ToString()); xpsColorContext.Commit(); } #endregion #region Fonts foreach (System.Windows.Xps.Packaging.XpsFont currentXpsFont in currentContentPageReader.Fonts) { System.Windows.Xps.Packaging.XpsFont xpsFont = contentPageWriter.AddFont(false); xpsFont.IsRestricted = false; System.IO.MemoryStream deobfuscatedStream = new System.IO.MemoryStream(); currentXpsFont.GetStream().CopyTo(deobfuscatedStream); String fontResourceName = currentXpsFont.Uri.ToString(); fontResourceName = fontResourceName.Split('/')[fontResourceName.Split('/').Length - 1]; if (fontResourceName.Contains(".odttf")) { fontResourceName = fontResourceName.Replace(".odttf", String.Empty); Guid fontGuid = new Guid(fontResourceName); deobfuscatedStream = CommonFunctions.XmlFontDeobfuscate(currentXpsFont.GetStream(), fontGuid); } System.IO.Stream xpsFontStream = xpsFont.GetStream(); // GET DESTINATION STREAM TO COPY TO deobfuscatedStream.CopyTo(xpsFontStream); // REMAP SOURCE URI pageContent = pageContent.Replace(currentXpsFont.Uri.ToString(), xpsFont.Uri.ToString()); xpsFont.Commit(); } #endregion #region Images foreach (System.Windows.Xps.Packaging.XpsImage currentXpsImage in currentContentPageReader.Images) { // FILE EXTENSION TO DETERMINE IMAGE TYPE System.Windows.Xps.Packaging.XpsImageType imageType = System.Windows.Xps.Packaging.XpsImageType.TiffImageType; String fileExtension = currentXpsImage.Uri.ToString().Split('.')[1]; switch (fileExtension.ToLower()) { case "jpeg": case "jpg": imageType = System.Windows.Xps.Packaging.XpsImageType.JpegImageType; break; case "png": imageType = System.Windows.Xps.Packaging.XpsImageType.PngImageType; break; case "wdp": imageType = System.Windows.Xps.Packaging.XpsImageType.WdpImageType; break; case "tif": case "tiff": default: imageType = System.Windows.Xps.Packaging.XpsImageType.TiffImageType; break; } System.Windows.Xps.Packaging.XpsImage xpsImage = contentPageWriter.AddImage(imageType); System.IO.Stream xpsImageStream = xpsImage.GetStream(); // GET DESTINATION STREAM TO COPY TO currentXpsImage.GetStream().CopyTo(xpsImageStream); // REMAP SOURCE URI pageContent = pageContent.Replace(currentXpsImage.Uri.ToString(), xpsImage.Uri.ToString()); // xpsImage.Uri = currentXpsImage.Uri; xpsImage.Commit(); } #endregion // COPY XAML CONTENT xmlPageWriter.WriteRaw(pageContent); contentPageWriter.Commit(); } contentDocumentWriter.Commit(); } } #endregion contentSequenceWriter.Commit(); renderedXpsDocument.Close(); xpsPackage.Close(); renderedImage.Image = renderedContent; renderedImage.Name = "EntityCorrespondence" + id.ToString() + ".xps"; renderedImage.Extension = "xps"; renderedImage.MimeType = "application/vnd.ms-xpsdocument"; renderedImage.IsCompressed = false; return(renderedImage); }
internal XpsDocumentWriter(System.Windows.Xps.Packaging.XpsDocument document) { }
public System.Windows.Xps.Packaging.XpsDocument TiffToXps() { System.Drawing.Image[] tiffPages = TiffPages(); // INITIALIZE XPS System.IO.MemoryStream xpsStream = new System.IO.MemoryStream(); System.IO.Packaging.Package xpsPackage = System.IO.Packaging.Package.Open(xpsStream, System.IO.FileMode.Create); System.Windows.Xps.Packaging.XpsDocument xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(xpsPackage); xpsDocument.Uri = new Uri("http://www.quebesystems.com", UriKind.Absolute); System.Windows.Xps.XpsDocumentWriter xpsWriter = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(xpsDocument); // SET UP XPS DOCUMENT AND FIRST FIXED DOCUMENT System.Windows.Xps.Packaging.IXpsFixedDocumentSequenceWriter xpsFixedDocumentSequenceWriter = xpsDocument.AddFixedDocumentSequence(); System.Windows.Xps.Packaging.IXpsFixedDocumentWriter xpsFixedDocumentWriter = xpsFixedDocumentSequenceWriter.AddFixedDocument(); // WRITE TIFF IMAGES AS PAGES IN XPS foreach (System.Drawing.Image currentTiffPage in tiffPages) { // ADD A NEW PAGE, THEN EMBED IMAGE TO THE PAGE System.Windows.Xps.Packaging.IXpsFixedPageWriter xpsFixedPageWriter = xpsFixedDocumentWriter.AddFixedPage(); System.Windows.Xps.Packaging.XpsImage xpsImage = xpsFixedPageWriter.AddImage(System.Windows.Xps.Packaging.XpsImageType.TiffImageType); System.IO.Stream xpsImageStream = xpsImage.GetStream(); // GET DESTINATION STREAM TO COPY TO // COPY TIFF IMAGE TO XPS IMAGE currentTiffPage.Save(xpsImageStream, System.Drawing.Imaging.ImageFormat.Tiff); xpsImage.Commit(); // IMAGE IS EMBED, BUT PAGE HAS NOT BEEN CREATED, CREATE PAGE System.Xml.XmlWriter xmlPageWriter = xpsFixedPageWriter.XmlWriter; xmlPageWriter.WriteStartElement("FixedPage"); // XPS PAGE STARTS WITH A FIXED PAGE TAG xmlPageWriter.WriteAttributeString("xmlns", "http://schemas.microsoft.com/xps/2005/06"); xmlPageWriter.WriteAttributeString("xml:lang", "en-US"); xmlPageWriter.WriteAttributeString("Width", currentTiffPage.Width.ToString()); xmlPageWriter.WriteAttributeString("Height", currentTiffPage.Height.ToString()); xmlPageWriter.WriteStartElement("Path"); xmlPageWriter.WriteAttributeString("Data", "M 0,0 H " + currentTiffPage.Width.ToString() + " V " + currentTiffPage.Height.ToString() + " H 0 z"); xmlPageWriter.WriteStartElement("Path.Fill"); xmlPageWriter.WriteStartElement("ImageBrush"); xmlPageWriter.WriteAttributeString("TileMode", "None"); xmlPageWriter.WriteAttributeString("ViewboxUnits", "Absolute"); xmlPageWriter.WriteAttributeString("ViewportUnits", "Absolute"); xmlPageWriter.WriteAttributeString("Viewbox", "0, 0, " + currentTiffPage.Width.ToString() + ", " + currentTiffPage.Height.ToString()); xmlPageWriter.WriteAttributeString("Viewport", "0, 0, " + currentTiffPage.Width.ToString() + ", " + currentTiffPage.Height.ToString()); xmlPageWriter.WriteAttributeString("ImageSource", xpsImage.Uri.ToString()); xmlPageWriter.WriteEndElement(); // IMAGE BRUSH xmlPageWriter.WriteEndElement(); // PATH.FILL xmlPageWriter.WriteEndElement(); // PATH // PAGE END ELEMENT xmlPageWriter.WriteEndElement(); // FIXED PAGE // PAGE COMMIT xpsFixedPageWriter.Commit(); } // COMMIT DOCUMENT WRITER xpsFixedDocumentWriter.Commit(); xpsFixedDocumentSequenceWriter.Commit(); xpsDocument.Close(); xpsPackage.Close(); //System.IO.FileStream fileStream = new System.IO.FileStream (@"C:\MERCURY\TEST7.XPS", System.IO.FileMode.Create); //fileStream.Write (xpsStream.ToArray (), 0, Convert.ToInt32 (xpsStream.Length)); //fileStream.Flush (); //fileStream.Close (); String contentUriName = ("memorystream://content" + Guid.NewGuid().ToString().Replace("-", "") + ".xps"); Uri contentUri = new Uri(contentUriName, UriKind.Absolute); System.IO.Packaging.Package attachmentPackage = System.IO.Packaging.Package.Open(xpsStream); System.IO.Packaging.PackageStore.AddPackage(contentUri, attachmentPackage); System.Windows.Xps.Packaging.XpsDocument xpsContent = new System.Windows.Xps.Packaging.XpsDocument(attachmentPackage, System.IO.Packaging.CompressionOption.Normal, contentUriName); return(xpsContent); }
/// <summary> /// 方法2 /// </summary> /// <param name="wordFilename"></param> /// <param name="xpsFilename"></param> /// <param name="err"></param> /// <returns></returns> public static System.Windows.Xps.Packaging.XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename, out string err) { err = ""; // Create a WordApplication and host word document Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); try { wordApp.Documents.Open(wordFilename); // To Invisible the word document wordApp.Application.Visible = false; // Minimize the opened word document wordApp.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize; Microsoft.Office.Interop.Word.Document doc = wordApp.ActiveDocument; doc.SaveAs(xpsFilename, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXPS); System.Windows.Xps.Packaging.XpsDocument xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(xpsFilename, FileAccess.Read); return xpsDocument; } catch (Exception ex) { err = "wordDocName:" + wordFilename + ",xpsDocName:" + xpsFilename + ",err:" + ex.Message; return null; } finally { wordApp.Documents.Close(); ((Microsoft.Office.Interop.Word._Application)wordApp).Quit(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges); } }
//文档装载预览 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(); } }
public override Dictionary <string, string> Validate() { Dictionary <String, String> validationResponse = new Dictionary <string, string> (); switch (contentType) { case Enumerations.CorrespondenceContentType.Report: if (String.IsNullOrWhiteSpace(Name)) { validationResponse.Add("Report or Attachment Name", "Empty or NULL."); } break; case Enumerations.CorrespondenceContentType.Attachment: String fileExtension = String.Empty; if ((String.IsNullOrWhiteSpace(attachmentBase64)) || (name.Split('.').Length < 2)) { validationResponse.Add("Attachment", "Not found."); } else { try { fileExtension = name.Split('.')[name.Split('.').Length - 1]; switch (fileExtension.ToLower()) { case "pdf": PdfSharp.Pdf.PdfDocument pdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(Attachment); // validationResponse.Add ("Attachment", "PDF file format not supported at this time."); break; case "xps": System.IO.Packaging.Package attachmentPackage = System.IO.Packaging.Package.Open(Attachment); System.Windows.Xps.Packaging.XpsDocument xpsContent = new System.Windows.Xps.Packaging.XpsDocument(attachmentPackage); validationResponse.Add("Attachment", "XPS file format not supported at this time."); break; default: validationResponse.Add("Attachment", "Unknown or unsupported file format [" + fileExtension + "]."); break; } if (!String.IsNullOrWhiteSpace(attachmentXpsBase64)) { try { System.IO.Packaging.Package attachmentPackage = System.IO.Packaging.Package.Open(AttachmentXps); System.Windows.Xps.Packaging.XpsDocument xpsContent = new System.Windows.Xps.Packaging.XpsDocument(attachmentPackage); } catch (Exception attachmentException) { #if DEBUG System.Diagnostics.Debug.WriteLine(attachmentException.Message); #endif validationResponse.Add("Attachment XPS", "Unable to successfully open and parse XPS Attachment."); } } } catch (Exception attachmentException) { #if DEBUG System.Diagnostics.Debug.WriteLine(attachmentException.Message); #endif validationResponse.Add("Attachment", "Unknown or unsupported file format [" + fileExtension + "]."); } } break; } return(validationResponse); }
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); }
/// <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(); } }