Close() публичный Метод

public Close ( ) : void
Результат void
Пример #1
0
        public void CreateCodeBaseXML()
        {
            try
            {
                package = Package.Open(fileCodeBase);

                XmlDocument sharedString = GetPartFile(OfficeFilePart.ShareString, 0);
                sharedString.Save(Common.SHARED_STRING);
                XmlDocument sheet = GetPartFile(OfficeFilePart.Sheet, 1);

                XsltArgumentList xsltArgListSheet = new XsltArgumentList();
                XsltSettings settings = new XsltSettings(true, true);
                XslCompiledTransform xslTransSheet = new XslCompiledTransform();
                xslTransSheet.Load(Common.XSLT_CODE_BASE, settings, new XmlUrlResolver());
                xsltArgListSheet.AddParam("prmDocSharedStrings", "", sharedString.CreateNavigator());
                string sOutXmlSheet = System.String.Empty;
                using (FileStream fs = new FileStream(Common.XML_CODE_BASE, FileMode.Create))
                {
                    xslTransSheet.Transform(sheet.CreateNavigator(), xsltArgListSheet, fs);
                }

                XslCompiledTransform xslRowSheet = new XslCompiledTransform();
                xslRowSheet.Load(Common.XSLT_TO_ROW);
                xslRowSheet.Transform(Common.XML_CODE_BASE, Common.XML_ROW);

            }
            finally
            {
                package.Close();
            }
        }
Пример #2
0
        public static void ExportVisualAsPdf(MainWindowViewModel usefulDataVM)
        {
            //Set up the WPF Control to be printed
            UserControl1 controlToPrint;

            controlToPrint             = new UserControl1();
            controlToPrint.DataContext = usefulDataVM;


            PageContent pageContent = new PageContent();
            FixedPage   fixedPage   = new FixedPage();



            fixedPage.Children.Add(controlToPrint);
            ((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);



            SaveFileDialog sfd = new SaveFileDialog
            {
                DefaultExt = ".pdf",
                Filter     = "PDF Documents (.pdf)|*.pdf"
            };

            bool?result = sfd.ShowDialog();

            if (result != true)
            {
                return;
            }



            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);

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

            var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(memoryStream);

            //public static void Convert(Stream xpsInStream, Stream pdfOutStream, bool closePdfStream);
            XpsConverter.Convert(pdfXpsDoc, sfd.FileName, 0);
            Process.Start(sfd.FileName);
        }
Пример #3
0
        public static void DoItTTT()
        {
            string filename    = "c:\\tmp\\goof.xps";
            string newFilename = "c:\\tmp\\new_goof.xps";

            XpsDocument xpsOld = new XpsDocument(filename, System.IO.FileAccess.Read);

            System.Windows.Documents.FixedDocumentSequence seqOld = xpsOld.GetFixedDocumentSequence();
            System.IO.Packaging.Package container = System.IO.Packaging.Package.Open(newFilename, System.IO.FileMode.Create);
            XpsDocumentWriter           writer    = XpsDocument.CreateXpsDocumentWriter(new XpsDocument(container));

            System.Windows.Documents.Serialization.SerializerWriterCollator vxpsd = writer.CreateVisualsCollator();
            int pageno = 1;

            foreach (System.Windows.Documents.DocumentReference r in seqOld.References)
            {
                System.Windows.Documents.FixedDocument d = r.GetDocument(false);
                foreach (System.Windows.Documents.PageContent pc in d.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();
                    ContainerVisual newpage = new ContainerVisual();
                    newpage.Children.Add(fixedPage);
                    newpage.Children.Add(CreateWatermark(400, 400, "hello world"));
                    pageno++;
                    vxpsd.Write(newpage);
                }
            }
            vxpsd.EndBatchWrite();
            container.Close();
            xpsOld.Close();
        }
        public static void ExportVisualAsPdf(Visual visual)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                DefaultExt = ".pdf",
                Filter     = "PDF Documents (.pdf)|*.pdf"
            };

            bool?result = saveFileDialog.ShowDialog();

            if (result != true)
            {
                return;
            }

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

                xpsDocumentWriter.Write(visual);


                xpsDocument.Close();

                var packageUri = new Uri("memorystream://myXps.xps");
                PackageStore.AddPackage(packageUri, package);
                XpsDocument doc = new XpsDocument(package, CompressionOption.SuperFast, packageUri.AbsoluteUri);
                XpsConverter.Convert(doc, saveFileDialog.FileName, 0);

                package.Close();
                //var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(memoryStream);
                //XpsConverter.Convert(pdfXpsDoc, saveFileDialog.FileName, 0);
            }
        }
Пример #5
0
 public static void ReleasePackage(Package package)
 {
     lock (m_Lock)
     {
         string key = null;
         foreach (KeyValuePair<string, Package> pair in m_Packages)
         {
             if (pair.Value == package)
             {
                 key = pair.Key;
                 break;
             }
         }
         if (key != null)
         {
             package.Close();
             m_Packages.Remove(key);
         }
     }
 }
Пример #6
0
        protected XDocument SaveDoc(MemoryStream result, Package pkg, PackagePart part, XmlReader xmlReader, XDocument xmlMainXMLDoc, string templateBody)
        {
            xmlMainXMLDoc = XDocument.Parse(templateBody);

            var partWrt = new StreamWriter(part.GetStream(FileMode.Open, FileAccess.ReadWrite));
            xmlMainXMLDoc.Save(partWrt);

            partWrt.Flush();
            partWrt.Close();
            pkg.Close();

            result.Position = 0;

            xmlReader.Close();
            return xmlMainXMLDoc;
        }
Пример #7
0
        private void SignAllParts(Package package, X509Certificate2 certificate)
        {
            var partsToSign = new List<Uri>();
            var relationshipsToSign = new List<PackageRelationshipSelector>();

            foreach (var relationship in package.GetRelationshipsByType(RtOfficeDocument))
            {
                AddSignableItems(relationship, partsToSign, relationshipsToSign);
            }

            var mgr = new PackageDigitalSignatureManager(package)
            {
                CertificateOption = CertificateEmbeddingOption.InSignaturePart
            };

            var officeObject = CreateOfficeObject(SignatureID, ManifestHashAlgorithm);
            var officeObjectReference = new Reference("#" + OfficeObjectID);
            mgr.Sign(partsToSign,
                     certificate,
                     relationshipsToSign,
                     SignatureID,
                     new[] { officeObject },
                     new[] { officeObjectReference });
            package.Close();
        }
Пример #8
0
        /// <summary>
        /// Exports the framework element to an image.
        /// </summary>
        /// <param name="frameworkElement">exported framework element</param>
        /// <param name="method">image format</param>
        /// <param name="filename">file name</param>
        /// <param name="title">image title</param>
        /// <param name="useFrameAndCaption"></param>
        /// <param name="boundingRectangle">bounding rectangle</param>
        public void ExportToImage(FrameworkElement frameworkElement, EExportToImageMethod method, string filename, string title, bool useFrameAndCaption,
                                  Rect?boundingRectangle = null)
        {
            const int bounds     = 10;
            const int textoffset = 20;

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

                RenderTargetBitmap rtb;

                if (!boundingRectangle.HasValue)
                {
                    boundingRectangle = new Rect(0, 0, frameworkElement.ActualWidth, frameworkElement.ActualHeight);
                }

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

                frameworkElement.InvalidateVisual();
                DrawingVisual  drawingVisual  = new DrawingVisual();
                DrawingContext drawingContext = drawingVisual.RenderOpen();
                drawingContext.DrawRectangle(ViewToolkitResources.WhiteBrush, null, new Rect(0, 0, rtb.Width, rtb.Height));
                VisualBrush canvasBrush = new VisualBrush(frameworkElement)
                {
                    Stretch = Stretch.None, AlignmentX = 0, 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(-boundingRectangle.Value.Left, -boundingRectangle.Value.Top, boundingRectangle.Value.Width + boundingRectangle.Value.Left, boundingRectangle.Value.Height + boundingRectangle.Value.Top));
                }
                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)
            {
                {
                    if (!boundingRectangle.HasValue)
                    {
                        boundingRectangle = new Rect(0, 0, frameworkElement.ActualWidth, frameworkElement.ActualHeight);
                    }

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


                    // Get the size of the canvas
                    Size size = new Size(boundingRectangle.Value.Width, boundingRectangle.Value.Height);
                    // Measure and arrange elements
                    frameworkElement.Measure(size);
                    frameworkElement.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(frameworkElement);
                    // Close document
                    doc.Close();
                    // Close package
                    package.Close();

                    // Restore previously saved layout
                    frameworkElement.LayoutTransform = transform;
                }
            }
        }
        /// <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>
        /// <param name="direction">Document Flow Direction</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,
            FlowDirection direction = FlowDirection.LeftToRight)
        {
            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;
                        reportPage.FlowDirection = direction;

                        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();
                        newFixedPage.FlowDirection = direction;

                        PageContent pageContent = new PageContent();
                        pageContent.FlowDirection = direction;

                        ((IAddChild)pageContent).AddChild(newFixedPage);

                        fixedDocument.Pages.Add(pageContent);
                    }

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

                    var packageUri = new Uri("memorystream://myXps.xps");
                    PackageStore.AddPackage(packageUri, package);
                    XpsDocument doc = new XpsDocument(package, CompressionOption.SuperFast, packageUri.AbsoluteUri);

                    XpsConverter.Convert(doc, saveFileDialog.FileName, 0);

                    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();
            }
        }
Пример #10
0
        internal static void PostCreation(Package package, DocumentTypes documentType = DocumentTypes.Document)
        {
            XDocument mainDoc, stylesDoc, numberingDoc;

            #region MainDocumentPart
            // Create the main document part for this package
            PackagePart mainDocumentPart;
            if (documentType == DocumentTypes.Document)
            {
                mainDocumentPart = package.CreatePart(new Uri("/word/document.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
            }
            else
            {
                mainDocumentPart = package.CreatePart(new Uri("/word/document.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml");
            }
            package.CreateRelationship(mainDocumentPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");

            // Load the document part into a XDocument object
            using (TextReader tr = new StreamReader(mainDocumentPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
            {
                mainDoc = XDocument.Parse
                (@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
                   <w:document xmlns:ve=""http://schemas.openxmlformats.org/markup-compatibility/2006"" xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:m=""http://schemas.openxmlformats.org/officeDocument/2006/math"" xmlns:v=""urn:schemas-microsoft-com:vml"" xmlns:wp=""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"" xmlns:w10=""urn:schemas-microsoft-com:office:word"" xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"" xmlns:wne=""http://schemas.microsoft.com/office/word/2006/wordml"" xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
                   <w:body>
                    <w:sectPr w:rsidR=""003E25F4"" w:rsidSect=""00FC3028"">
                        <w:pgSz w:w=""11906"" w:h=""16838""/>
                        <w:pgMar w:top=""1440"" w:right=""1440"" w:bottom=""1440"" w:left=""1440"" w:header=""708"" w:footer=""708"" w:gutter=""0""/>
                        <w:cols w:space=""708""/>
                        <w:docGrid w:linePitch=""360""/>
                    </w:sectPr>
                   </w:body>
                   </w:document>"
                );
            }

            // Save the main document
            using (TextWriter tw = new StreamWriter(mainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)))
                mainDoc.Save(tw, SaveOptions.None);
            #endregion

            #region StylePart
            stylesDoc = HelperFunctions.AddDefaultStylesXml(package);
            #endregion

            #region NumberingPart
            numberingDoc = HelperFunctions.AddDefaultNumberingXml(package);
            #endregion

            package.Close();
        }
Пример #11
0
        // Methods
        public List<string> GetObjectIds()
        {
            try
            {
                package = Package.Open(fileCodeBase);

                XmlDocument idObjects = GetPartFile(OfficeFilePart.Sheet, 1);
                XmlNamespaceManager xnm = new XmlNamespaceManager(idObjects.NameTable);
                xnm.AddNamespace("def", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");

                List<string> listString = new List<string>();
                XmlNodeList elemList = idObjects.SelectNodes("//def:row/def:c[starts-with(@r, 'C')]/def:v", xnm);

                for (int i = 2; i < elemList.Count; i++)
                    listString.Add(elemList[i].InnerXml);

                return listString.Distinct().ToList();
            }
            finally
            {
                package.Close();
            }
        }