Пример #1
0
        private void AddFonts(IXpsFixedPageReader fixedPageReader, IXpsFixedPageWriter pageWriter)
        {
            // Adding font from source to resources.
            foreach (XpsFont font in fixedPageReader.Fonts)
            {
                if (!CheckIfFontAddedAlready(font.Uri.ToString()))
                {
                    XpsFont newFont = pageWriter.AddFont(false);

                    using (Stream dstFontStream = newFont.GetStream())
                    {
                        using (Stream srcFontStream = font.GetStream())
                        {
                            if (font.IsObfuscated)
                            {
                                WriteObfuscatedStream(font.Uri.ToString(),
                                                      dstFontStream, srcFontStream);
                            }
                            else
                            {
                                WriteToStream(dstFontStream, srcFontStream);
                            }
                            newFont.Commit();
                            XpsDetails xpsFont = new XpsDetails();
                            xpsFont.resource  = newFont;
                            xpsFont.sourceURI = font.Uri;
                            xpsFont.destURI   = newFont.Uri;
                            xpsFonts.Add(xpsFont);
                        }
                    }
                }
            }
        }
Пример #2
0
        //<SnippetCreateAndWriteToXpsDocument>
        // ---------------------------- Create() ------------------------------
        /// <summary>
        ///   Creates an XpsDocument using the Xps.Packaging APIs.</summary>
        /// <param name="xpsDocument">
        ///   The XpsDocument to create.</param>
        /// <remarks>
        ///   The Xps.Packaging APIs are used to create the DocumentSequence,
        ///   FixedDocument, and FixedPage "PackageParts" of an XpsDocument.
        ///   The applicationt is responsible for using the XmlWriter to
        ///   serialize the page markup and for supplying the streams for any
        ///   font or image resources.</remarks>
        public void Create(XpsDocument xpsDocument)
        {
            // Create the document sequence
            IXpsFixedDocumentSequenceWriter docSeqWriter =
                xpsDocument.AddFixedDocumentSequence();

            // Create the document
            IXpsFixedDocumentWriter docWriter = docSeqWriter.AddFixedDocument();

            // Create the Page
            IXpsFixedPageWriter pageWriter = docWriter.AddFixedPage();

            // Get the XmlWriter
            XmlWriter xmlWriter = pageWriter.XmlWriter;

            // Write the mark up according the XPS Specifications
            BeginFixedPage(xmlWriter);
            AddGlyphRun(pageWriter, xmlWriter,
                        "This is a photo of the famous Notre Dame in Paris",
                        16, 50, 50, @"C:\Windows\fonts\arial.ttf");

            AddImage(pageWriter, xmlWriter,
                     "ParisNotreDame.jpg", XpsImageType.JpegImageType,
                     100, 100, 600, 1100);

            // End the page.
            EndFixedPage(xmlWriter);

            // Close the page, document, and document sequence.
            pageWriter.Commit();
            docWriter.Commit();
            docSeqWriter.Commit();
            _fontDictionary.Clear();
        }// end:Create()
Пример #3
0
        private void AddContent(IXpsFixedPageReader fixedPageReader, IXpsFixedPageWriter pageWriter)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(fixedPageReader.XmlReader);
            EditXPSContent(xmlDoc.ChildNodes);
            xmlDoc.Save(pageWriter.XmlWriter);
        }
        /// <summary>
        /// Add images from source to new XPS.
        /// </summary>
        /// <param name="fixedPageReader"></param>
        /// <param name="pageWriter"></param>
        private void AddImages(
            IXpsFixedPageReader fixedPageReader,
            IXpsFixedPageWriter pageWriter)
        {
            // Adding images to resources.
            foreach (XpsImage image in fixedPageReader.Images)
            {
                XpsImage newImage = null;

                // Getting the URI to check the image extension.
                string sourceExt = image.Uri.ToString().ToLower();


                if (sourceExt.Contains(ImageType.PNG))
                {
                    newImage = pageWriter.AddImage(XpsImageType.PngImageType);
                }
                else if (sourceExt.Contains(ImageType.JPG) ||
                         sourceExt.Contains(ImageType.JPEG))
                {
                    newImage = pageWriter.AddImage(XpsImageType.JpegImageType);
                }
                else if (sourceExt.Contains(ImageType.TIF) ||
                         sourceExt.Contains(ImageType.TIFF))
                {
                    newImage = pageWriter.AddImage(XpsImageType.TiffImageType);
                }
                else if (sourceExt.Contains(ImageType.WDP))
                {
                    newImage = pageWriter.AddImage(XpsImageType.WdpImageType);
                }
                else
                {
                    newImage = null;
                }

                if (null != newImage)
                {
                    using (Stream dstImageStream = newImage.GetStream())
                    {
                        using (Stream srcImageStream = image.GetStream())
                        {
                            CopyStream(srcImageStream, dstImageStream);
                            newImage.Commit();
                            XpsDetails xpsImage = new XpsDetails();
                            xpsImage.resource  = newImage;
                            xpsImage.sourceURI = image.Uri;
                            xpsImage.destURI   = newImage.Uri;
                            xpsImages.Add(xpsImage);
                        }
                    }
                }
            }
        }
Пример #5
0
    AddPageResources(IXpsFixedPageWriter fixedPageWriter)
    {
        // Collection of all resources for this page.
        //   Key: "XpsImage", "XpsFont"
        //   Value: List of XpsImage or XpsFont
        Dictionary <string, List <XpsResource> > resources =
            new Dictionary <string, List <XpsResource> >();

        // Collections of images and fonts used in the current page.
        List <XpsResource> xpsImages = new List <XpsResource>();
        List <XpsResource> xpsFonts  = new List <XpsResource>();

        try
        {
            XpsImage xpsImage;
            XpsFont  xpsFont;

            // Add, Write, and Commit image1 to the current page.
            xpsImage = fixedPageWriter.AddImage(XpsImageType.JpegImageType);
            WriteToStream(xpsImage.GetStream(), image1);
            xpsImage.Commit();
            xpsImages.Add(xpsImage);    // Add image1 as a required resource.

            // Add, Write, and Commit font 1 to the current page.
            xpsFont = fixedPageWriter.AddFont();
            WriteObfuscatedStream(
                xpsFont.Uri.ToString(), xpsFont.GetStream(), font1);
            xpsFont.Commit();
            xpsFonts.Add(xpsFont);      // Add font1 as a required resource.

            // Add, Write, and Commit image2 to the current page.
            xpsImage = fixedPageWriter.AddImage(XpsImageType.TiffImageType);
            WriteToStream(xpsImage.GetStream(), image2);
            xpsImage.Commit();
            xpsImages.Add(xpsImage);    // Add image2 as a required resource.

            // Add, Write, and Commit font2 to the current page.
            xpsFont = fixedPageWriter.AddFont(false);
            WriteToStream(xpsFont.GetStream(), font2);
            xpsFont.Commit();
            xpsFonts.Add(xpsFont);      // Add font2 as a required resource.

            // Return the image and font resources in a combined collection.
            resources.Add("XpsImage", xpsImages);
            resources.Add("XpsFont", xpsFonts);
            return(resources);
        }
        catch (XpsPackagingException xpsException)
        {
            throw xpsException;
        }
    }// end:AddPageResources()
        /// <summary>
        /// Add content from source to new XPS.
        /// </summary>
        /// <param name="fixedPageReader"></param>
        /// <param name="pageWriter"></param>
        private void AddContent(
            IXpsFixedPageReader fixedPageReader,
            IXpsFixedPageWriter pageWriter)
        {
            XmlDocument xmlDoc = new XmlDocument();

            // Loading XPS content.
            xmlDoc.Load(fixedPageReader.XmlReader);

            // Find and replace text to edit the XPS.
            EditXPSContent(xmlDoc.ChildNodes);

            // Writing the modified XML content to a new XPS doc.
            xmlDoc.Save(pageWriter.XmlWriter);
        }
Пример #7
0
        }// end:AddImage()

        // --------------------------- GetXpsImage() --------------------------
        /// <summary>
        ///   Copies a given image to a specified XPS page.</summary>
        /// <param name="pageWriter">
        ///   The FixedPage writer to copy the image to.</param>
        /// <param name="imgPath">
        ///   The source file path for the image.</param>
        /// <param name="imageType">
        ///   The type of the image.</param>
        /// <returns>
        ///   The package URI of the copied image.</returns>
        private string GetXpsImage(
            IXpsFixedPageWriter pageWriter,
            string imgPath,
            XpsImageType imageType)
        {
            XpsImage xpsImage  = pageWriter.AddImage(imageType);
            Stream   srcStream = new FileStream(imgPath, FileMode.Open);
            Stream   dstStream = xpsImage.GetStream();

            Byte[] streamBytes = new Byte[srcStream.Length];
            srcStream.Read(streamBytes, 0, (int)srcStream.Length);
            dstStream.Write(streamBytes, 0, (int)srcStream.Length);
            xpsImage.Commit();
            return(xpsImage.Uri.ToString());
        }
Пример #8
0
        // --------------------------- AddGlyphRun() --------------------------
        /// <summary>
        ///   Outputs a glyph run to a given XmlWriter.</summary>
        /// <param name="pageWriter">
        ///   The XpsFixePageWriter for accessing the page fonts.</param>
        /// <param name="writer">
        ///   The XmlWriter to output the glyph markup to.</param>
        /// <param name="text">
        ///   The text of the glyph run.</param>
        /// <param name="size">
        ///   The font size.</param>
        /// <param name="x">
        ///   The X location of the glyph run.</param>
        /// <param name="y">
        ///   The Y location of the glyph run.</param>
        /// <param name="fontUri">
        ///   The path to font file.</param>
        private void AddGlyphRun(
            IXpsFixedPageWriter pageWriter,
            XmlWriter writer,
            string text,
            int size,
            int x, int y,
            string fontUri)
        {
            string packageFontUri = GetXpsFont(pageWriter, fontUri);

            writer.WriteStartElement("Glyphs");
            writer.WriteAttributeString("OriginX", x.ToString());
            writer.WriteAttributeString("OriginY", y.ToString());
            writer.WriteAttributeString("FontRenderingEmSize", size.ToString());
            writer.WriteAttributeString("FontUri", packageFontUri);
            writer.WriteAttributeString("UnicodeString", text);
            writer.WriteAttributeString("Fill", "#FFFFE4C4");
            writer.WriteEndElement();
        }// end:AddGlyphRun()
Пример #9
0
    }// end:AddPackageContent()

    //</SnippetXpsCreateAddPkgContent>

    //<SnippetXpsCreateAddDocContent>
    // ------------------------- AddDocumentContent ---------------------------
    /// <summary>
    ///   Adds a predefined set of content to a given document writer.</summary>
    /// <param name="fixedDocumentWriter">
    ///   The document writer to add the content to.</param>
    private void AddDocumentContent(IXpsFixedDocumentWriter fixedDocumentWriter)
    {
        // Collection of image and font resources used on the current page.
        //   Key: "XpsImage", "XpsFont"
        //   Value: List of XpsImage or XpsFont resources
        Dictionary <string, List <XpsResource> > resources;

        try
        {
            // Add Page 1 to current document.
            IXpsFixedPageWriter fixedPageWriter =
                fixedDocumentWriter.AddFixedPage();

            // Add the resources for Page 1 and get the resource collection.
            resources = AddPageResources(fixedPageWriter);

            // Write page content for Page 1.
            WritePageContent(fixedPageWriter.XmlWriter,
                             "Page 1 of " + fixedDocumentWriter.Uri.ToString(), resources);

            // Commit Page 1.
            fixedPageWriter.Commit();

            // Add Page 2 to current document.
            fixedPageWriter = fixedDocumentWriter.AddFixedPage();

            // Add the resources for Page 2 and get the resource collection.
            resources = AddPageResources(fixedPageWriter);

            // Write page content to Page 2.
            WritePageContent(fixedPageWriter.XmlWriter,
                             "Page 2 of " + fixedDocumentWriter.Uri.ToString(), resources);

            // Commit Page 2.
            fixedPageWriter.Commit();
        }
        catch (XpsPackagingException xpsException)
        {
            throw xpsException;
        }
    }// end:AddDocumentContent()
Пример #10
0
        }// end:GetXpsFont()

        // ---------------------------- AddImage() ----------------------------
        /// <summary>
        ///   Outputs the markup for adding an image.</summary>
        /// <param name="pageWriter">
        ///   The FixedPageWriter associated for getting the image.</param>
        /// <param name="writer">   The XmlWriter to output to.</param>
        /// <param name="imgPath">  The image path.</param>
        /// <param name="imageType">The image type</param>
        /// <param name="x">        The X position of the image.</param>
        /// <param name="y">        The Y position of the image.</param>
        /// <param name="height">   The height of the image.</param>
        /// <param name="width">    The width of the image.</param>
        private void AddImage(
            IXpsFixedPageWriter pageWriter,
            XmlWriter writer,
            string imgPath,
            XpsImageType imageType,
            float x, float y,
            float height,
            float width)
        {
            // Write the surrounding path.
            writer.WriteStartElement("Path");

            // Form the path data string.
            // M="Move To"(start), L="Line To", Z="Close shape"
            string pathData =
                String.Format("M {0},{1} L {2},{3} {4},{5} {6},{7} z",
                              x, y,
                              x, y + height,
                              x + width, y + height,
                              x + width, y);

            writer.WriteAttributeString("Data", pathData);
            writer.WriteStartElement("Path.Fill");
            writer.WriteStartElement("ImageBrush");
            writer.WriteAttributeString("ImageSource",
                                        GetXpsImage(pageWriter, imgPath, imageType));
            string viewPort = String.Format("{0},{1},{2},{3}",
                                            0, 0, width, height);

            writer.WriteAttributeString("Viewport", viewPort);
            writer.WriteAttributeString("ViewportUnits", "Absolute");
            string viewBox = String.Format("{0},{1},{2},{3}",
                                           x, y, x + width, y + height);

            writer.WriteAttributeString("Viewbox", viewBox);
            writer.WriteAttributeString("ViewboxUnits", "Absolute");
            writer.WriteEndElement(); //ImageBrush
            writer.WriteEndElement(); //Path.Fill
            writer.WriteEndElement(); //Path
        }// end:AddImage()
Пример #11
0
        }// end:AddGlyphRun()

        // --------------------------- GetXpsFont() ---------------------------
        /// <summary>
        ///   Returns the relative path to a font part in the package.</summary>
        /// <param name="pageWriter">
        ///   The page to associate the font with.</param>
        /// <param name="fontUri">
        ///   The URI for the source font file.</param>
        /// <returns>
        ///   The relative path to font part in the package.</returns>
        /// <remarks>
        ///   If the font has not been added previously, GetXpsFont creates a
        ///   new font part and copies the font data from the specified
        ///   source font URI.</remarks>
        private string GetXpsFont(IXpsFixedPageWriter pageWriter, string fontUri)
        {
            string packageFontUri;

            if (_fontDictionary.ContainsKey(fontUri))
            {
                packageFontUri = _fontDictionary[fontUri];
            }
            else
            {
                XpsFont xpsFont   = pageWriter.AddFont(false);
                Stream  dstStream = xpsFont.GetStream();
                Stream  srcStream =
                    new FileStream(fontUri, FileMode.Open, FileAccess.Read);
                Byte[] streamBytes = new Byte[srcStream.Length];
                srcStream.Read(streamBytes, 0, (int)srcStream.Length);
                dstStream.Write(streamBytes, 0, (int)srcStream.Length);
                _fontDictionary[fontUri] = xpsFont.Uri.ToString();
                packageFontUri           = xpsFont.Uri.ToString();
                xpsFont.Commit();
            }
            return(packageFontUri);
        }// end:GetXpsFont()
        private bool CreateNewXPSFromSource()
        {
            bool blnResult = false;

            try
            {
                // Delete the old file generated by our code.
                if (File.Exists(destinationXpsPath))
                {
                    File.Delete(destinationXpsPath);
                }

                // Creating the output XPS file.
                XpsDocument document = new XpsDocument(destinationXpsPath,
                                                       FileAccess.ReadWrite,
                                                       System.IO.Packaging.CompressionOption.Maximum);
                IXpsFixedDocumentSequenceWriter docSeqWriter
                    = document.AddFixedDocumentSequence();

                // Loading the source xps files to list to read them for edit.
                List <string> sourceFiles = new List <string>();
                sourceFiles.Add(sourceXPS);

                // Looping each source files.
                foreach (string sourceFile in sourceFiles)
                {
                    XpsDocument docToRead = new XpsDocument(sourceFile, FileAccess.ReadWrite);
                    IXpsFixedDocumentSequenceReader docSequenceToRead =
                        docToRead.FixedDocumentSequenceReader;

                    foreach (IXpsFixedDocumentReader fixedDocumentReader in
                             docSequenceToRead.FixedDocuments)
                    {
                        IXpsFixedDocumentWriter fixedDocumentWriter =
                            docSeqWriter.AddFixedDocument();

                        AddStructure(fixedDocumentReader, fixedDocumentWriter);

                        foreach (IXpsFixedPageReader fixedPageReader in
                                 fixedDocumentReader.FixedPages)
                        {
                            IXpsFixedPageWriter pageWriter =
                                fixedDocumentWriter.AddFixedPage();

                            AddImages(fixedPageReader, pageWriter);

                            AddFonts(fixedPageReader, pageWriter);

                            AddContent(fixedPageReader, pageWriter);

                            // Commmit all changes.
                            pageWriter.Commit();
                        }
                        fixedDocumentWriter.Commit();
                    }
                    // Close the current source before openeing next one.
                    docToRead.Close();
                }

                docSeqWriter.Commit();

                // Show the modified content in a DocumentViewer.
                dvModifiedXPS.Document  = document.GetFixedDocumentSequence();
                ModifiedGrid.Visibility = System.Windows.Visibility.Visible;

                // Close newly created XPS document.
                document.Close();
                blnResult = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return(blnResult);
        }
Пример #13
0
        }// end:AddPackageContent()

        // ------------------------- AddDocumentContent ---------------------------
        /// <summary>
        ///   Adds a predefined set of content to a given document writer.</summary>
        /// <param name="fixedDocumentWriter">
        ///   The document writer to add the content to.</param>
        private void AddDocumentContent(IXpsFixedDocumentWriter fixedDocumentWriter)
        {
            // Collection of image and font resources used on the current page.
            //   Key: "XpsImage", "XpsFont"
            //   Value: List of XpsImage or XpsFont resources
            Dictionary <string, List <XpsResource> > resources;

            try
            {
                // Add Page 1 to current document.
                IXpsFixedPageWriter fixedPageWriter =
                    fixedDocumentWriter.AddFixedPage();

                // Add the resources for Page 1 and get the resource collection.
                // resources = AddPageResources(fixedPageWriter);

                // Write page content for Page 1.

                fixedPageWriter.XmlWriter.WriteStartElement("FixedPage");
                fixedPageWriter.XmlWriter.WriteAttributeString("Width", "816");
                fixedPageWriter.XmlWriter.WriteAttributeString("Height", "1056");
                fixedPageWriter.XmlWriter.WriteAttributeString("xmlns",
                                                               "http://schemas.microsoft.com/xps/2005/06");
                fixedPageWriter.XmlWriter.WriteAttributeString("xml:lang", "en-US");


                fixedPageWriter.XmlWriter.WriteStartElement("Table");

                fixedPageWriter.XmlWriter.WriteAttributeString("Margin", "6,16,0,0");

                fixedPageWriter.XmlWriter.WriteStartElement("Table.Columns");

                fixedPageWriter.XmlWriter.WriteStartElement("TableColumn");
                fixedPageWriter.XmlWriter.WriteAttributeString("Width", "63.5");
                fixedPageWriter.XmlWriter.WriteEndElement(); //column

                fixedPageWriter.XmlWriter.WriteStartElement("TableColumn");
                fixedPageWriter.XmlWriter.WriteAttributeString("Width", "3");
                fixedPageWriter.XmlWriter.WriteEndElement(); //column

                fixedPageWriter.XmlWriter.WriteStartElement("TableColumn");
                fixedPageWriter.XmlWriter.WriteAttributeString("Width", "63.5");
                fixedPageWriter.XmlWriter.WriteEndElement(); //column

                fixedPageWriter.XmlWriter.WriteStartElement("TableColumn");
                fixedPageWriter.XmlWriter.WriteAttributeString("Width", "3");
                fixedPageWriter.XmlWriter.WriteEndElement(); //column

                fixedPageWriter.XmlWriter.WriteStartElement("TableColumn");
                fixedPageWriter.XmlWriter.WriteAttributeString("Width", "63.5");
                fixedPageWriter.XmlWriter.WriteEndElement(); //column

                fixedPageWriter.XmlWriter.WriteEndElement(); //columns

                fixedPageWriter.XmlWriter.WriteStartElement("TableRowGroup");


                for (int i = 0; i < 7; i++)
                {
                    fixedPageWriter.XmlWriter.WriteStartElement("TableRow");

                    fixedPageWriter.XmlWriter.WriteStartElement("TableCell");

                    fixedPageWriter.XmlWriter.WriteElementString("Paragraph", "Hello!!!");

                    fixedPageWriter.XmlWriter.WriteEndElement(); //TableCell

                    fixedPageWriter.XmlWriter.WriteEndElement(); //row
                }


                fixedPageWriter.XmlWriter.WriteEndElement(); //TableRowGroup

                fixedPageWriter.XmlWriter.WriteEndElement(); //table

                // Commit Page 1.
                fixedPageWriter.Commit();
            }
            catch (XpsPackagingException xpsException)
            {
                throw xpsException;
            }
        }// end:AddDocumentContent()
Пример #14
0
        private static void AddDocumentContent(IXpsFixedDocumentWriter fixedDocumentWriter,
                                               XmlNodeList selectedThumbnails)
        {
            Console.WriteLine("Using PackWebRequest and PackWebResponse APIs to retrieve selected photos ...");
            Console.WriteLine("------------------------------------------------------------------------------");

            foreach (XmlNode node in selectedThumbnails)
            {
                Uri    packageUri;
                Uri    partUri;
                string selectedId = node.Attributes["Id"].InnerText;

                try
                {
                    GetSelectedPhotoUri(selectedId, out packageUri, out partUri);
                }
                catch (Exception e)
                {
                    // We catch all exceptions because we don't want any
                    // exception caused by invalid input crash our server.
                    // But we record all exceptions, and try to continue.
                    Console.WriteLine("Hit exception while resolving photo Uri "
                                      + "for selected thumbnail ID " + selectedId);
                    Console.WriteLine("Exception:");
                    Console.WriteLine(e.ToString());
                    continue;
                }

                // Using PackWebRequest to retrieve the photo.
                using (WebResponse response =
                           PackWebRequestForPhotoPart(packageUri, partUri))
                {
                    Stream s = response.GetResponseStream();

                    // Add a fixed page into the fixed document.
                    IXpsFixedPageWriter fixedPageWriter =
                        fixedDocumentWriter.AddFixedPage();

                    // Add the photo image resource to the page.
                    XpsImage xpsImage =
                        fixedPageWriter.AddImage(response.ContentType);

                    SharedLibrary.CopyStream(s, xpsImage.GetStream());

                    xpsImage.Commit();

                    s.Seek(0, SeekOrigin.Begin);

                    // Use BitmapFrame to get the dimension of the photo image.
                    BitmapFrame imgFrame = BitmapFrame.Create(s);

                    // Write the XML description of the fixed page.
                    WritePageContent(fixedPageWriter.XmlWriter, xpsImage.Uri,
                                     imgFrame);

                    fixedPageWriter.Commit();
                }
            }
            Console.WriteLine("------------------------------------------------------------------------------");
            Console.WriteLine("All selected photos retrieved.");
        }
Пример #15
0
        /// <summary>
        /// End current page and start with next page.
        /// </summary>
        /// <param name="format">Format of the next page.</param>
        /// <remarks>
        /// Attention: For each page you have to add the references to fonts and pictures!
        /// </remarks>
        public void NextPage(PageFormat format)
        {
            // Close current page
            _xpsPageWriter.Commit();

            // Create new page.
            _xpsPageWriter = _xpsDocWriter.AddFixedPage();
            _xmlWriter = _xpsPageWriter.XmlWriter;

            // Copy all Fonts
            var part = _package.GetPart(_xpsPageWriter.Uri);
            foreach (var uri in _embeddedFonts.Values)
                part.CreateRelationship(uri, TargetMode.Internal, RequiredResourceRelationship);

            // Copy all Images
            foreach (var img in _embeddedImages.Values)
                part.CreateRelationship(img.Uri, TargetMode.Internal, RequiredResourceRelationship);

            StartPage(format);
        }
Пример #16
0
        public bool CreateNewXPSFromSource(string sourceXpsPath, string destinationXpsPath, ReplaceCallBackType cb)
        {
            this.m_CallBack = cb;
            bool blnResult = false;

            try
            {
                // Delete the old file generated by our code.
                if (File.Exists(destinationXpsPath))
                {
                    File.Delete(destinationXpsPath);
                }

                // Creating the output XPS file.
                XpsDocument document = new XpsDocument(destinationXpsPath,
                                                       FileAccess.ReadWrite, System.IO.Packaging.CompressionOption.NotCompressed);

                IXpsFixedDocumentSequenceWriter docSeqWriter = document.AddFixedDocumentSequence();

                // Loading the source xps files to list to read them for edit.
                List <string> sourceFiles = new List <string>();
                sourceFiles.Add(sourceXpsPath);

                // Looping each source files.
                foreach (string sourceFile in sourceFiles)
                {
                    XpsDocument docToRead = new XpsDocument(sourceFile, FileAccess.ReadWrite);
                    IXpsFixedDocumentSequenceReader docSequenceToRead =
                        docToRead.FixedDocumentSequenceReader;

                    foreach (IXpsFixedDocumentReader fixedDocumentReader in
                             docSequenceToRead.FixedDocuments)
                    {
                        IXpsFixedDocumentWriter fixedDocumentWriter =
                            docSeqWriter.AddFixedDocument();

                        AddStructure(fixedDocumentReader, fixedDocumentWriter);

                        foreach (IXpsFixedPageReader fixedPageReader in
                                 fixedDocumentReader.FixedPages)
                        {
                            IXpsFixedPageWriter pageWriter =
                                fixedDocumentWriter.AddFixedPage();

                            AddImages(fixedPageReader, pageWriter);

                            AddFonts(fixedPageReader, pageWriter);

                            AddContent(fixedPageReader, pageWriter);

                            // Commmit all changes.
                            pageWriter.Commit();
                        }
                        fixedDocumentWriter.Commit();
                    }
                    // Close the current source before openeing next one.
                    docToRead.Close();
                }

                docSeqWriter.Commit();

                // Close newly created XPS document.
                document.Close();
                blnResult = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return(blnResult);
        }
Пример #17
0
        /// <summary>
        /// Creates a new XPS Diagram from scratch
        /// </summary>
        /// <param name="fileName">Name of the file. Important: If the file already exists, it will be deleted</param>
        /// <param name="format">Format of the page</param>
        public XpsDocumentHelper(string fileName, PageFormat format)
        {
            // Initialize teh Dictionaries for fonts and images
            _embeddedFonts = new Dictionary<string, Uri>();
            _embeddedImages = new Dictionary<string, ImageInfo>();

            // The file is created from scratch so if it already exists it will be removed.
            if (File.Exists(fileName))
                File.Delete(fileName);

            // Create the new package with all internal things that are required
            _package = Package.Open(fileName);
            _document = new XpsDocument(_package);
            _xpsDocSeqWriter = _document.AddFixedDocumentSequence();
            _xpsDocWriter = _xpsDocSeqWriter.AddFixedDocument();
            _xpsPageWriter = _xpsDocWriter.AddFixedPage();
            _xmlWriter = _xpsPageWriter.XmlWriter;

            // Write the document header, I fixed everything to the the en-US culture here.
            StartPage(format);
        }
Пример #18
0
        public bool WriteDocument(List <byte[]> images, string file_out)
        {
            XpsDocument doc = null;
            IXpsFixedDocumentSequenceWriter docSeqWriter = null;
            IXpsFixedDocumentWriter         docWriter    = null;

            if (LogHelper.CanDebug())
            {
                LogHelper.Begin("XpsHelper.WriteDocument");
            }
            try
            {
                // xps doc does not manage overwrite, so delete before if exist
                if (File.Exists(file_out))
                {
                    File.Delete(file_out);
                }

                // create the document
                doc = new XpsDocument(file_out, FileAccess.ReadWrite, CompressionOption.NotCompressed);

                // Create the document sequence
                docSeqWriter = doc.AddFixedDocumentSequence();

                // Create the document
                docWriter = docSeqWriter.AddFixedDocument();

                for (int i = 0; i < images.Count; ++i)
                {
                    // Create the Page
                    IXpsFixedPageWriter pageWriter = docWriter.AddFixedPage();

                    // Get the XmlWriter
                    XmlWriter xmlWriter = pageWriter.XmlWriter;

                    //create the xps image resource
                    XpsImage xpsImage = pageWriter.AddImage(XpsImageType.JpegImageType);
                    using (Stream dstImageStream = xpsImage.GetStream())
                    {
                        dstImageStream.Write(images[i], 0, images[i].Length);
                        xpsImage.Commit();
                    }

                    //this is just to get the real WPF image size as WPF display units and not image pixel size !!
                    using (MemoryStream ms = new MemoryStream(images[i]))
                    {
                        BitmapImage myImage = new BitmapImage();
                        myImage.BeginInit();
                        myImage.CacheOption  = BitmapCacheOption.OnLoad;
                        myImage.StreamSource = ms;
                        myImage.EndInit();

                        //write the page
                        WritePageContent(xmlWriter, xpsImage, myImage.Width, myImage.Height);
                    }

                    //with the first page, create the thumbnail of the xps document
                    if (i == 0)
                    {
                        XpsThumbnail thumb = doc.AddThumbnail(XpsImageType.JpegImageType);

                        using (MemoryStream ms = new MemoryStream(images[i]))
                        {
                            BitmapImage thumbImage = new BitmapImage();
                            thumbImage.BeginInit();
                            thumbImage.DecodePixelWidth = 256;
                            thumbImage.CacheOption      = BitmapCacheOption.OnLoad;
                            thumbImage.StreamSource     = ms;
                            thumbImage.EndInit();

                            using (Stream xpsThumbStream = thumb.GetStream())
                            {
                                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                                encoder.Frames.Add(BitmapFrame.Create(thumbImage));
                                encoder.Save(xpsThumbStream);
                            }
                        }
                        thumb.Commit();
                    }

                    xmlWriter.Flush();

                    // Close the page
                    pageWriter.Commit();
                }

                return(true);
            }
            catch (Exception err)
            {
                LogHelper.Manage("XpsHelper.WriteDocument", err);
                return(false);
            }
            finally
            {
                if (docWriter != null)
                {
                    docWriter.Commit();
                }

                if (docSeqWriter != null)
                {
                    docSeqWriter.Commit();
                }

                if (doc != null)
                {
                    doc.Close();
                }

                LogHelper.End("XpsHelper.WriteDocument");
            }
        }