Example #1
0
        private static void CreatePart(System.IO.Packaging.Package package, string path, Stream sourceStream)
        {
            if (PackageHelper.IsManifest(path))
            {
                return;
            }

            Uri uri = UriUtility.CreatePartUri(path);

            // Create the part
            var packagePart = package.CreatePart(uri, DefaultContentType, System.IO.Packaging.CompressionOption.Maximum);

            using (Stream stream = packagePart.GetStream())
            {
                sourceStream.CopyTo(stream);
            }
        }
Example #2
0
 private void WriteFiles(System.IO.Packaging.Package package)
 {
     // Add files that might not come from expanding files on disk
     foreach (IPackageFile file in new HashSet <IPackageFile>(Files))
     {
         using (Stream stream = file.GetStream())
         {
             try
             {
                 CreatePart(package, file.Path, stream);
             }
             catch
             {
                 throw;
             }
         }
     }
 }
Example #3
0
 /// <summary>
 /// Сохранение конфигурации
 /// </summary>
 /// <returns>True если успешно</returns>
 public bool SaveConfiguration()
 {
     try
     {
         using (System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(CONFIGURATION_FILENAME, FileMode.Create, FileAccess.Write))
         {
             // Коллекция элементов
             byte[] bytes = JsonSerializer.JsonSerializeToBytes(ActiveSession.BalancePoints, _callBackAction);
             SaveJsonDataToPart(bytes, package, PART_BalancePoints);
             // Словарь пар код группы - формула расчёта баланса
             bytes = JsonSerializer.JsonSerializeToBytes(BalanceGroupsFormulaById, _callBackAction);
         }
     }
     catch (Exception ex)
     {
         _callBackAction(ex);
         return(false);
     }
     return(true);
 }
Example #4
0
        public string CreateXps(int i)
        {
            if (i < 0 && i >= tempPagesToShow.ToArray().Length)
                return null;

            FileStream fs = new FileStream(xpspath + _pagename[i] + ".xps", FileMode.OpenOrCreate);

            FixedPage page = tempPagesToShow[i];



            System.IO.Packaging.Package np = System.IO.Packaging.Package.Open(fs, FileMode.OpenOrCreate, FileAccess.ReadWrite);



            XpsDocument xpsdoc = new XpsDocument(np);

      
       
            _pageurls.Add(xpspath + _pagename[i] + ".xps");

            


           

           XpsDocumentWriter docWriter = XpsDocument.CreateXpsDocumentWriter(xpsdoc);
            docWriter.Write(page);

            
            xpsdoc.Close();
            np.Close();
            fs.Dispose();
            fs.Close();
            

            return xpspath + _pagename[i] + ".xps";
        }
Example #5
0
        public void ShowDocument(string file)
        {
            YellowstonePathology.Business.OrderIdParser orderIdParser = new Business.OrderIdParser(file);
            string fileName = YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser);

            fileName += file + ".xps";

            FileStream fileStream = File.OpenRead(fileName);

            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            fileStream.Close();
            MemoryStream memoryStream = new MemoryStream(bytes);

            string tempPath = "pack://" + file + ".xps";

            System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream);
            m_Uri = new Uri(tempPath);
            System.IO.Packaging.PackageStore.AddPackage(m_Uri, package);
            m_Document = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum, tempPath);
            FixedDocumentSequence fixedDocumentSequence = m_Document.GetFixedDocumentSequence();

            this.DocumentViewerReports.Document = fixedDocumentSequence as IDocumentPaginatorSource;
        }
 protected PackagePart(System.IO.Packaging.Package package, System.Uri partUri, string contentType)
 {
 }
 protected PackagePart(System.IO.Packaging.Package package, System.Uri partUri)
 {
 }
        /// <summary>
        /// Загрузка сессии
        /// </summary>
        /// <param name="fileName">Имя файла, если не указано, то загрузка из стандартного файла <see cref="BALANCE_SESSION_FILENAME"/></param>
        /// <returns>True если загрузка произошла успешно</returns>
        private bool LoadSessionData(string fileName = null)
        {
            bool mustStoreLastSessionFileName = true;

            try
            {
                if (String.IsNullOrWhiteSpace(fileName))
                {
                    fileName = BALANCE_SESSION_FILENAME + SESSION_FILE_EXTENSION;
                    mustStoreLastSessionFileName = false;
                }
                else
                if (Path.GetExtension(fileName).ToLowerInvariant() != SESSION_FILE_EXTENSION)
                {
                    fileName = fileName + SESSION_FILE_EXTENSION;
                }

                var fi = new FileInfo(Path.Combine(SESSIONS_FOLDER, fileName));
                if (fi.Exists == false)
                {
                    return(false);
                }

                BalanceSession balanceSession = null;

                bool isOldVersionFile = false;
                try
                {
                    if (Path.IsPathRooted(fileName) == false)
                    {
                        fileName = Path.Combine(SESSIONS_FOLDER, fileName);
                    }

                    // попытка прочитать файл как пакет
                    using (System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(fileName, FileMode.Open, FileAccess.Read))
                    {
                        BalanceSessionInfo info = LoadSessionInfoFromPackage(package.GetPart(System.IO.Packaging.PackUriHelper.CreatePartUri(new Uri(PART_Info, UriKind.Relative))));
                        if (IsSupportedSessionVersion(info.Version))
                        {
                            void unknownVersion()
                            {
                                string msg = String.Format("Файл '{1}'\nнеизвестной версии - {0}\nЗагрузка невозможна.\nОбновите программу или обратитесь к разработчику.", info.Version, fi.FullName);

                                EmcosSiteWrapperApp.LogError(msg);
                                EmcosSiteWrapperApp.ShowError(msg);
                            }

                            switch (info.Version.Major)
                            {
                            case 1:
                                switch (info.Version.Minor)
                                {
                                case 0:
                                    isOldVersionFile = true;
                                    break;

                                case 1:
                                    balanceSession = LoadDataFromFileVersion_1_1(package);
                                    break;

                                default:
                                    unknownVersion();
                                    return(false);
                                }
                                break;

                            default:
                                unknownVersion();
                                return(false);
                            }
                        }
                    }
                }
                catch (IOException ioe)
                {
                    EmcosSiteWrapperApp.LogException(ioe);
                    isOldVersionFile = true;
                }
                catch (Exception e) { isOldVersionFile = true; }

                if (isOldVersionFile)
                {
                    balanceSession = LoadDataFromFileVersion_1_0(fi.FullName);
                }

                if (mustStoreLastSessionFileName)
                {
                    File.WriteAllText(Path.Combine(SESSIONS_FOLDER, "lastsession"), fileName);
                }

                ActiveSession = balanceSession;
                return(balanceSession != null);
            }
            catch (Exception ex)
            {
                _callBackAction(ex);
                ActiveSession = null;
                return(false);
            }
        }
Example #9
0
        /// <summary>
        /// Exports the diagram to an image.
        /// </summary>
        /// <param name="method">image format</param>
        /// <param name="filename">file name</param>
        /// <param name="title">diagram title</param>
        /// <param name="useFrameAndCaption"></param>
        public void ExportToImage(EExportToImageMethod method, string filename, string title, bool useFrameAndCaption)
        {
            const int bounds     = 10;
            const int textoffset = 20;

            #if DEBUG
            Visibility labelVisible = MouseLabel.Visibility;
            MouseLabel.Visibility = Visibility.Collapsed;
            #endif

            if (method == EExportToImageMethod.PNG || method == EExportToImageMethod.PNGClipBoard)
            {
                FormattedText titleText = new FormattedText(title, new CultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 20, Brushes.Gray);

                double canvasWidth;
                double canvasHeight;
                GetCanvasWidthAndHeight(out canvasWidth, out canvasHeight);

                RenderTargetBitmap rtb;

                if (useFrameAndCaption)
                {
                    rtb = new RenderTargetBitmap((int)(Math.Max(bounds + canvasWidth + bounds, textoffset + titleText.Width + textoffset)), (int)(textoffset + titleText.Height + textoffset + canvasHeight + bounds), 96, 96, PixelFormats.Pbgra32);
                }
                else
                {
                    rtb = new RenderTargetBitmap((int)(canvasWidth), (int)(canvasHeight), 96, 96, PixelFormats.Pbgra32);
                }

                this.InvalidateVisual();
                DrawingVisual  drawingVisual  = new DrawingVisual();
                DrawingContext drawingContext = drawingVisual.RenderOpen();
                drawingContext.DrawRectangle(this.Background, null, new Rect(0, 0, rtb.Width, rtb.Height));
                VisualBrush canvasBrush = new VisualBrush(this);
                canvasBrush.Stretch    = Stretch.None;
                canvasBrush.AlignmentX = 0;
                canvasBrush.AlignmentY = 0;
                if (useFrameAndCaption)
                {
                    Rect rect = new Rect(bounds, textoffset + titleText.Height + textoffset, rtb.Width - 2 * bounds, rtb.Height - bounds - textoffset - titleText.Height - textoffset);
                    drawingContext.DrawRectangle(canvasBrush, new Pen(Brushes.LightGray, 1), rect);
                    drawingContext.DrawText(titleText, new Point(rtb.Width / 2 - titleText.Width / 2, textoffset));
                }
                else
                {
                    drawingContext.DrawRectangle(canvasBrush, null, new Rect(0, 0, (canvasWidth), (canvasHeight)));
                }
                drawingContext.Close();

                rtb.Render(drawingVisual);
                PngBitmapEncoder png = new PngBitmapEncoder();
                png.Frames.Add(BitmapFrame.Create(rtb));
                if (method == EExportToImageMethod.PNG)
                {
                    using (Stream stm = File.Create(filename))
                    {
                        png.Save(stm);
                    }
                }
                if (method == EExportToImageMethod.PNGClipBoard)
                {
                    Clipboard.SetImage(rtb);
                }
            }
            else if (method == EExportToImageMethod.XPS)
            {
                {
                    double canvasWidth;
                    double canvasHeight;
                    GetCanvasWidthAndHeight(out canvasWidth, out canvasHeight);


                    // Save current canvas transorm
                    Transform transform = this.LayoutTransform;
                    // Temporarily reset the layout transform before saving
                    this.LayoutTransform = null;


                    // Get the size of the canvas
                    Size size = new Size(canvasWidth, canvasHeight);
                    // Measure and arrange elements
                    this.Measure(size);
                    this.Arrange(new Rect(size));

                    // Open new package
                    System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(filename, FileMode.Create);
                    // Create new xps document based on the package opened
                    XpsDocument doc = new XpsDocument(package);
                    // Create an instance of XpsDocumentWriter for the document
                    XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
                    // Write the canvas (as Visual) to the document
                    writer.Write(this);
                    // Close document
                    doc.Close();
                    // Close package
                    package.Close();

                    // Restore previously saved layout
                    this.LayoutTransform = transform;
                }
            }

            #if DEBUG
            MouseLabel.Visibility = labelVisible;
            #endif
        }
Example #10
0
 public System.Collections.Generic.List <System.IO.Packaging.PackageRelationship> Select(System.IO.Packaging.Package package)
 {
     throw null;
 }
Example #11
0
        /// <summary>
        /// Сохранение сессии
        /// </summary>
        /// <param name="fileName">Имя файла, если не указано, то загрузка из стандартного файла <see cref="BALANCE_SESSION_FILENAME"/></param>
        /// <returns>True если загрузка произошла успешно</returns>
        private bool SaveSessionData(string fileName = null)
        {
            if (ActiveSession == null)
            {
                throw new InvalidOperationException();
            }

            bool mustStoreLastSessionFileName = false;

            if (String.IsNullOrWhiteSpace(fileName))
            {
                fileName = BALANCE_SESSION_FILENAME + SESSION_FILE_EXTENSION;
                try
                {
                    if (File.Exists(Path.Combine(SESSIONS_FOLDER, "lastsession")))
                    {
                        File.Delete(Path.Combine(SESSIONS_FOLDER, "lastsession"));
                    }
                }
                catch (IOException ex)
                {
                    _callBackAction(ex);
                }
            }
            else
            {
                if (fileName.EndsWith(".bak") == false)
                {
                    fileName = fileName + SESSION_FILE_EXTENSION;
                    mustStoreLastSessionFileName = true;
                }
            }

            ActiveSession.Info.FileName = fileName;

            using (System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite))
            {
                // Общая информация
                byte[] bytes = JsonSerializer.JsonSerializeToBytes(ActiveSession.Info, _callBackAction);
                SaveJsonDataToPart(bytes, package, PART_Info);
                // Коллекция элементов
                bytes = JsonSerializer.JsonSerializeToBytes(ActiveSession.BalancePoints, _callBackAction);
                SaveJsonDataToPart(bytes, package, PART_BalancePoints);

                SaveJsonDataToPart(bytes, package, PART_BalanceGroupsFormulaById);
                // Словарь пар код группы - баланс активной энергии
                bytes = JsonSerializer.JsonSerializeToBytes(ActiveSession.ActiveEnergyBalanceById, _callBackAction);
                SaveJsonDataToPart(bytes, package, PART_ActiveEnergyBalanceById);
                // Словарь пар код группы - баланс реактивной энергии
                bytes = JsonSerializer.JsonSerializeToBytes(ActiveSession.ReactiveEnergyBalanceById, _callBackAction);
                SaveJsonDataToPart(bytes, package, PART_ReactiveEnergyBalanceById);
                // Словарь пар код элемента - активная энергия
                bytes = JsonSerializer.JsonSerializeToBytes(ActiveSession.ActiveEnergyById, _callBackAction);
                SaveJsonDataToPart(bytes, package, PART_ActiveEnergyById);
                // Словарь пар код элемента - реактивная энергия
                bytes = JsonSerializer.JsonSerializeToBytes(ActiveSession.ReactiveEnergyById, _callBackAction);
                SaveJsonDataToPart(bytes, package, PART_ReactiveEnergyById);
                // Словарь пар код элемента - описание
                bytes = JsonSerializer.JsonSerializeToBytes(ActiveSession.DescriptionsById, _callBackAction);
                SaveJsonDataToPart(bytes, package, PART_DescriptionsById);
            }

            if (JsonSerializer.GzJsonSerialize(
                    ActiveSession,
                    Path.Combine(SESSIONS_FOLDER, fileName),
                    _callBackAction) == false)
            {
                return(false);
            }

            // сохранение имени файла последней сессии
            if (mustStoreLastSessionFileName)
            {
                File.WriteAllText(Path.Combine(SESSIONS_FOLDER, "lastsession"), fileName);
            }
            return(true);
        }
        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);
        }
 protected PackagePart(System.IO.Packaging.Package package, System.Uri partUri, string contentType, System.IO.Packaging.CompressionOption compressionOption)
 {
 }
Example #14
0
        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);
        }
Example #15
0
        public static PresentationDocument Open(System.IO.Packaging.Package package)
        {
            IPackage packageAdapt = new PackageAdapt(package);

            return(PresentationDocument.Open(packageAdapt));
        }
Example #16
0
        public static void Main(string[] args)
        {
            // Output information on how to use the command line tool if not given enough arguments.
            if (args.Length < 3)
            {
                System.Console.WriteLine("Visual Studio Extension Signer");
                System.Console.WriteLine("This tool is used to digitally sign a vsix file with a pfx certificate.");
                System.Console.WriteLine();
                System.Console.WriteLine("Usage:  VsixSigner <PfxFilePath> <PfxPassword> <VsixFilePath>");
                System.Console.WriteLine("  PfxFilePath     Path to the PFX certificate file to sign with.");
                System.Console.WriteLine("  PfxPassword     The password assigned to the PFX file.");
                System.Console.WriteLine("  VsixFilePath    Path to the VSIX file to digitally sign.");
                return;
            }

            // Fetch and validate the PFX file path.
            string pfxFilePath = args[0];

            if (string.IsNullOrEmpty(pfxFilePath))
            {
                System.Console.WriteLine("You must provide a valid path to a PFX file.");
                System.Environment.ExitCode = -1;
                return;
            }
            if (System.IO.File.Exists(pfxFilePath) == false)
            {
                System.Console.WriteLine("PFX file not found: " + pfxFilePath);
                System.Environment.ExitCode = -1;
                return;
            }

            // Fetch the PFX password.
            string pfxPassword = args[1];

            if (pfxPassword == null)
            {
                pfxPassword = string.Empty;
            }

            // Fetch and validate the path to the VSIX file.
            string vsixFilePath = args[2];

            if (string.IsNullOrEmpty(vsixFilePath))
            {
                System.Console.WriteLine("You must provide a valid path to the VSIX file to digitally sign.");
                System.Environment.ExitCode = -1;
                return;
            }
            if (System.IO.File.Exists(vsixFilePath) == false)
            {
                System.Console.WriteLine("VSIX file not found: " + pfxFilePath);
                System.Environment.ExitCode = -1;
                return;
            }

            // Digitally sign the VSIX file's contents.
            bool wasSigned = false;

            System.IO.Packaging.Package vsixPackage = null;
            try
            {
                // Set up the signature manager.
                vsixPackage = System.IO.Packaging.Package.Open(vsixFilePath, System.IO.FileMode.Open);
                var signatureManager = new System.IO.Packaging.PackageDigitalSignatureManager(vsixPackage);
                signatureManager.CertificateOption = System.IO.Packaging.CertificateEmbeddingOption.InSignaturePart;

                // Create a collection of paths to all of VSIX file's internal files to be signed.
                var vsixPartPaths = new System.Collections.Generic.List <System.Uri>();
                foreach (var packagePart in vsixPackage.GetParts())
                {
                    vsixPartPaths.Add(packagePart.Uri);
                }
                vsixPartPaths.Add(
                    System.IO.Packaging.PackUriHelper.GetRelationshipPartUri(signatureManager.SignatureOrigin));
                vsixPartPaths.Add(signatureManager.SignatureOrigin);
                vsixPartPaths.Add(
                    System.IO.Packaging.PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

                // Create digital signatures for all of the VSIX's internal files/parts.
                var certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxFilePath, pfxPassword);
                signatureManager.Sign(vsixPartPaths, certificate);

                // Verify that the VSIX file was correctly signed.
                if (signatureManager.IsSigned &&
                    (signatureManager.VerifySignatures(true) == System.IO.Packaging.VerifyResult.Success))
                {
                    wasSigned = true;
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Environment.ExitCode = -1;
                return;
            }
            finally
            {
                if (vsixPackage != null)
                {
                    try { vsixPackage.Close(); }
                    catch (Exception) { }
                }
            }

            // If the digital signatures applied to the VSIX are invalid, then notify the user.
            if (wasSigned == false)
            {
                System.Console.WriteLine("The digital signatures applied to the VSIX file are invalid.");
                System.Environment.ExitCode = -1;
                return;
            }

            // Signing was successful.
            System.Console.WriteLine("Successfully signed the VSIX file.");
        }
Example #17
0
        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);
        }
 public System.Collections.Generic.List <System.IO.Packaging.PackageRelationship> Select(System.IO.Packaging.Package package)
 {
     return(default(System.Collections.Generic.List <System.IO.Packaging.PackageRelationship>));
 }
Example #19
0
        /// <summary>
        /// Divides elements of reportContainer into pages and exports them as PDF
        /// </summary>
        /// <param name="reportContainer">StackPanel containing report elements</param>
        /// <param name="dataContext">Data Context used in the report</param>
        /// <param name="margin">Margin of a report page</param>
        /// <param name="orientation">Landscape or Portrait orientation</param>
        /// <param name="resourceDictionary">Resources used in report</param>
        /// <param name="backgroundBrush">Brush that will be used as background for report page</param>
        /// <param name="reportHeaderDataTemplate">
        /// Optional header for each page
        /// Note: You can use DynamicResource PageNumber in this template to display page number
        /// </param>
        /// <param name="headerOnlyOnTheFirstPage">Use header only on the first page (default is false)</param>
        /// <param name="reportFooterDataTemplate">
        /// Optional footer for each page
        /// Note: You can use DynamicResource PageNumber in this template to display page number
        /// </param>
        /// <param name="footerStartsFromTheSecondPage">Do not use footer on the first page (default is false)</param>
        public static void ExportReportAsPdf(
            StackPanel reportContainer,
            object dataContext,
            Thickness margin,
            ReportOrientation orientation,
            ResourceDictionary resourceDictionary = null,
            Brush backgroundBrush = null,
            DataTemplate reportHeaderDataTemplate = null,
            bool headerOnlyOnTheFirstPage         = false,
            DataTemplate reportFooterDataTemplate = null,
            bool footerStartsFromTheSecondPage    = false)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                DefaultExt = ".pdf",
                Filter     = "PDF Documents (.pdf)|*.pdf"
            };

            bool?result = saveFileDialog.ShowDialog();

            if (result != true)
            {
                return;
            }

            Size reportSize = GetReportSize(reportContainer, margin, orientation);

            List <FrameworkElement> ReportElements = new List <FrameworkElement>(reportContainer.Children.Cast <FrameworkElement>());

            reportContainer.Children.Clear(); //to avoid exception "Specified element is already the logical child of another element."

            List <ReportPage> ReportPages =
                GetReportPages(
                    resourceDictionary,
                    backgroundBrush,
                    ReportElements,
                    dataContext,
                    margin,
                    reportSize,
                    reportHeaderDataTemplate,
                    headerOnlyOnTheFirstPage,
                    reportFooterDataTemplate,
                    footerStartsFromTheSecondPage);

            FixedDocument fixedDocument = new FixedDocument();

            try
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream, FileMode.Create);
                    XpsDocument       xpsDocument       = new XpsDocument(package);
                    XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);

                    foreach (Grid reportPage in ReportPages.Select(reportPage => reportPage.LayoutRoot))
                    {
                        reportPage.Width  = reportPage.ActualWidth;
                        reportPage.Height = reportPage.ActualHeight;

                        FixedPage newFixedPage = new FixedPage();
                        newFixedPage.Children.Add(reportPage);
                        newFixedPage.Measure(reportSize);
                        newFixedPage.Arrange(new Rect(reportSize));
                        newFixedPage.Width      = newFixedPage.ActualWidth;
                        newFixedPage.Height     = newFixedPage.ActualHeight;
                        newFixedPage.Background = backgroundBrush;
                        newFixedPage.UpdateLayout();

                        PageContent pageContent = new PageContent();
                        ((IAddChild)pageContent).AddChild(newFixedPage);

                        fixedDocument.Pages.Add(pageContent);
                    }

                    xpsDocumentWriter.Write(fixedDocument);
                    xpsDocument.Close();
                    package.Close();

                    var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(memoryStream);
                    XpsConverter.Convert(pdfXpsDoc, saveFileDialog.FileName, 0);
                }
            }
            finally
            {
                ReportPages.ForEach(reportPage => reportPage.ClearChildren());
                ReportElements.ForEach(elm => reportContainer.Children.Add(elm));
                reportContainer.UpdateLayout();
            }
        }