private static void CleanWorksheetRelsDocument(Package excelPackage, string sheetName) { string worksheetRelsFilePath = @"xl\worksheets\_rels\" + sheetName + ".rels"; PackagePart worksheetRelsPart = GetPackagePart(excelPackage, worksheetRelsFilePath); if (worksheetRelsPart != null) { XmlDocument worksheetRelsDocument = GetXmlDocumentFromPackagePart(worksheetRelsPart); List<XmlNode> nodesToRemove = new List<XmlNode>(); foreach (XmlNode worksheetRelsNode in worksheetRelsDocument.DocumentElement.ChildNodes) { if (worksheetRelsNode.Attributes["TargetMode"] != null) { // remove relationships to external files if (worksheetRelsNode.Attributes["TargetMode"].Value == "External") { nodesToRemove.Add(worksheetRelsNode); } } } if (nodesToRemove.Count > 0) { RemoveNodes(nodesToRemove); SaveXmlDocumentToPackagePart(worksheetRelsPart, worksheetRelsDocument); } } }
private void ShowPrintPreview() { // We have to clone the FlowDocument before we use different pagination settings for the export. RichTextDocument document = (RichTextDocument)fileService.ActiveDocument; FlowDocument clone = document.CloneContent(); clone.ColumnWidth = double.PositiveInfinity; // Create a package for the XPS document MemoryStream packageStream = new MemoryStream(); package = Package.Open(packageStream, FileMode.Create, FileAccess.ReadWrite); // Create a XPS document with the path "pack://temp.xps" PackageStore.AddPackage(new Uri(PackagePath), package); xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, PackagePath); // Serialize the XPS document XpsSerializationManager serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false); DocumentPaginator paginator = ((IDocumentPaginatorSource)clone).DocumentPaginator; serializer.SaveAsXaml(paginator); // Get the fixed document sequence FixedDocumentSequence documentSequence = xpsDocument.GetFixedDocumentSequence(); // Create and show the print preview view PrintPreviewViewModel printPreviewViewModel = printPreviewViewModelFactory.CreateExport().Value; printPreviewViewModel.Document = documentSequence; previousView = shellViewModel.ContentView; shellViewModel.ContentView = printPreviewViewModel.View; shellViewModel.IsPrintPreviewVisible = true; printPreviewCommand.RaiseCanExecuteChanged(); }
private static void CopyPackage(Package inputPackage, Package outputPackage) { foreach (var inputPart in inputPackage.GetParts()) { CreateNewPart(inputPart, outputPackage); } }
private void UpdatePackageManifest(Package package, PackagePart updatedPart) { if (package == null) throw new ArgumentNullException(nameof(package)); if (updatedPart == null) throw new ArgumentNullException(nameof(updatedPart)); if (package.FileOpenAccess != FileAccess.ReadWrite) throw new InvalidOperationException("Package must be open for reading and writing"); var manifestRelation = package.GetRelationship("MANIFEST"); var manifestPart = package.GetPart(manifestRelation.TargetUri); // parse manifest var manifest = new PackageManifest(manifestPart, null); // rehash updated part var csDefPart = manifest.Items.FirstOrDefault(i => i.PartUri == updatedPart.Uri); if (csDefPart == null) throw new InvalidOperationException(string.Format("Unable to find part '{0}' in package manifest", updatedPart.Uri)); csDefPart.Hash = manifest.HashAlgorithm.ComputeHash(updatedPart.GetStream(FileMode.Open, FileAccess.Read)); ; csDefPart.ModifiedDate = DateTime.UtcNow; var manifestStream = manifestPart.GetStream(FileMode.Open, FileAccess.Write); manifest.WriteToStream(manifestStream); }
public static bool CreateDocSettings(Package pkg, string sDataSource) { PackagePart prt; Stream stm = StmCreatePart(pkg, "/word/settings.xml", s_sUriContentTypeSettings, out prt); XmlTextWriter xw = new XmlTextWriter(stm, System.Text.Encoding.UTF8); StartElement(xw, "settings"); WriteElementFull(xw, "view", new[] {"web"}); StartElement(xw, "mailMerge"); WriteElementFull(xw, "mainDocumentType", new[] {"email"}); WriteElementFull(xw, "linkToQuery", (string[])null); WriteElementFull(xw, "dataType", new[] {"textFile"}); WriteElementFull(xw, "connectString", new[] {""}); WriteElementFull(xw, "query", new[] {String.Format("SELECT * FROM {0}", sDataSource)}); PackageRelationship rel = prt.CreateRelationship( new System.Uri(String.Format("file:///{0}", sDataSource), UriKind.Absolute), TargetMode.External, s_sUriMailMergeRelType); StartElement(xw, "dataSource"); xw.WriteAttributeString("id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships", rel.Id); EndElement(xw); StartElement(xw, "odso"); StartElement(xw, "fieldMapData"); WriteElementFull(xw, "type", new[] {"dbColumn"}); WriteElementFull(xw, "name", new[] {"email"}); WriteElementFull(xw, "mappedName", new[] {"E-mail Address"}); WriteElementFull(xw, "column", new[] {"0"}); WriteElementFull(xw, "lid", new[] {"en-US"}); EndElement(xw); // fieldMapData EndElement(xw); // odso EndElement(xw); // mailMerge EndElement(xw); // settings xw.Flush(); stm.Flush(); return true; }
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(); } }
private void ZipDirectory(string SourceFolderPath, Package package,int deviceType) { DirectoryInfo dir = new DirectoryInfo(SourceFolderPath); FileInfo[] files=dir.GetFiles(); foreach (FileInfo fi in files) { if ((".tdb".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && deviceType == 1) || (".dat".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && deviceType == 2) || (".doc".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && deviceType == 2) || ".crd".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) || deviceType == 3) { string relativePath = fi.FullName.Replace(SourceFolderPath, string.Empty); relativePath = relativePath.Replace("\\", "/"); Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(relativePath, UriKind.Relative)); //resourcePath="Resource\Image.jpg" //Uri partUriResource = PackUriHelper.CreatePartUri(new Uri(resourcePath, UriKind.Relative)); PackagePart part = package.CreatePart(partUriDocument, System.Net.Mime.MediaTypeNames.Application.Zip); using (FileStream fs = fi.OpenRead()) { using (Stream partStream = part.GetStream()) { CopyStream(fs, partStream); fs.Close(); partStream.Close(); } } } } DirectoryInfo[] directories = dir.GetDirectories(); foreach (DirectoryInfo subDi in directories) { ZipDirectory(SourceFolderPath, package, deviceType); } }
/// <summary> /// Creates a new instance of the ExcelPackage class based on a existing file or creates a new file. /// </summary> /// <param name="newFile">If newFile exists, it is opened. Otherwise it is created from scratch.</param> private ExcelPackage(FileInfo newFile) { _outputFolderPath = newFile.DirectoryName; if (newFile.Exists) { // open the existing package _package = Package.Open(newFile.FullName, FileMode.Open, FileAccess.ReadWrite); } else { // create a new package and add the main workbook.xml part _package = Package.Open(newFile.FullName, FileMode.Create, FileAccess.ReadWrite); // save a temporary part to create the default application/xml content type var uriDefaultContentType = new Uri("/default.xml", UriKind.Relative); var partTemp = _package.CreatePart(uriDefaultContentType, "application/xml"); var workbook = Workbook.WorkbookXml; // this will create the workbook xml in the package // create the relationship to the main part _package.CreateRelationship(Workbook.WorkbookUri, TargetMode.Internal, schemaRelationships + "/officeDocument"); // remove the temporary part that created the default xml content type _package.DeletePart(uriDefaultContentType); } }
private static void ExportMatrixPart(Package package, WfProcessDescriptor processDesp, WfExportProcessDescriptorContext context) { var matrix = WfMatrixAdapter.Instance.LoadByProcessKey(processDesp.Key, false); if (matrix == null) return; matrix.Loaded = true; Uri partUri = CreatePartUri(context.MatrixCounter.ToString(), WfProcessDescriptorPackagePartType.MatrixPart); if (context.ExistingParts.Contains(partUri.ToString())) return; context.MappingInfo.Add(new WfPackageRelationMapping() { MatrixPath = partUri.ToString(), MatrixDefID = matrix.Definition.Key, ProcessDescriptionID = processDesp.Key }); ExportMatrixDefPart(package, matrix.Definition, context); PackagePart part = package.CreatePart(partUri, MediaTypeNames.Application.Octet, CompressionOption.Normal); using (MemoryStream bytes = matrix.ExportToExcel2007(context.ExportParams.MatrixRoleAsPerson)) { using (Stream stream = part.GetStream()) { bytes.CopyTo(stream); } } context.ExistingParts.Add(partUri.ToString()); context.MatrixCounter++; }
public bool Open(string path) { try { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); memStream = new MemoryStream(); memStream.Write(buffer, 0, (int)fs.Length); buffer = null; fs.Close(); package = Package.Open(memStream, FileMode.Open, FileAccess.ReadWrite); docParts = new Dictionary<string, DocumentPart>(); PackagePartCollection parts = package.GetParts(); foreach (PackagePart part in parts) { DocumentPart docPart = new DocumentPart(part); docParts.Add(part.Uri.ToString(), docPart); } filePath = path; dirty = false; return true; } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); return false; } }
/// <summary> /// CertificatePart constructor /// </summary> internal CertificatePart(System.IO.Packaging.Package container, Uri partName) { if (container == null) { throw new ArgumentNullException("container"); } if (partName == null) { throw new ArgumentNullException("partName"); } partName = PackUriHelper.ValidatePartUri(partName); // create if not found if (container.PartExists(partName)) { // open the part _part = container.GetPart(partName); // ensure the part is of the expected type if (_part.ValidatedContentType().AreTypeAndSubTypeEqual(_certificatePartContentType) == false) { throw new FileFormatException(SR.CertificatePartContentTypeMismatch); } } else { // create the part _part = container.CreatePart(partName, _certificatePartContentType.ToString()); } }
void ExtractLayouts(Package package, PackageDefinition manifest, string workingDirectory) { var localContentDirectory = Path.Combine(workingDirectory, AzureCloudServiceConventions.PackageFolders.LocalContent); fileSystem.EnsureDirectoryExists(localContentDirectory); foreach (var layout in manifest.Layouts) { if (!layout.Name.StartsWith(AzureCloudServiceConventions.RoleLayoutPrefix)) continue; var layoutDirectory = Path.Combine(localContentDirectory, layout.Name.Substring(AzureCloudServiceConventions.RoleLayoutPrefix.Length)); fileSystem.EnsureDirectoryExists(layoutDirectory); foreach (var fileDefinition in layout.FileDefinitions) { var contentDefinition = manifest.GetContentDefinition(fileDefinition.Description.DataContentReference); var destinationFileName = Path.Combine(layoutDirectory, fileDefinition.FilePath.TrimStart('\\')); ExtractPart( package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), contentDefinition.Description.DataStorePath)), destinationFileName); } } }
XpsDocument( Package package, CompressionOption compressionOption ) : this(package, compressionOption, null) { }
void AddContent(Package package, PackageDefinition manifest, Uri partUri, string file) { var part = package.CreatePart( PackUriHelper.CreatePartUri(partUri), System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum); using (var partStream = part.GetStream()) using (var fileStream = fileSystem.OpenFile(file, FileMode.Open)) { fileStream.CopyTo(partStream); partStream.Flush(); fileStream.Position = 0; var hashAlgorithm = new SHA256Managed(); hashAlgorithm.ComputeHash(fileStream); manifest.Contents.Add(new ContentDefinition { Name = partUri.ToString(), Description = new ContentDescription { DataStorePath = partUri, LengthInBytes = (int) fileStream.Length, HashAlgorithm = IntegrityCheckHashAlgorithm.Sha256, Hash = Convert.ToBase64String(hashAlgorithm.Hash) } }); } }
public void Generate(Package sourcePackage, Package targetPackage, FileInfo outputFile) { var serializer = new XmlSerializer(typeof(DataSchemaModel)); var uri = PackUriHelper.CreatePartUri(new Uri("/replication.xml", UriKind.Relative)); var sourceModel = (DataSchemaModel)serializer.Deserialize(sourcePackage.GetPart(uri).GetStream()); var targetModel = (DataSchemaModel)serializer.Deserialize(targetPackage.GetPart(uri).GetStream()); var outputFileSql = new List<string>(); foreach (var publicationToCreate in sourceModel.Model.Elements.Except(targetModel.Model.Elements, x => x.Name)) { var createPublicationStep = new CreatePublicationStep(publicationToCreate); outputFileSql.AddRange(createPublicationStep.GenerateTSQL()); } foreach (var publicationToAlter in sourceModel.Model.Elements.Intersect(targetModel.Model.Elements, x => x.Name)) { var sqlPublicationComparer = new SqlPublicationComparer(); var matchingPublicationInTarget = targetModel.Model.Elements.Single(x => x.Name == publicationToAlter.Name); var alterPublicationStep = new AlterPublicationStep(sqlPublicationComparer.Compare(publicationToAlter, matchingPublicationInTarget)); outputFileSql.AddRange(alterPublicationStep.GenerateTSQL()); } foreach (var publicationToDrop in targetModel.Model.Elements.Except(sourceModel.Model.Elements, x => x.Name)) { var dropPublicationStep = new DropPublicationStep(publicationToDrop); outputFileSql.AddRange(dropPublicationStep.GenerateTSQL()); } }
/// <summary> /// CA1063 recomendation match /// </summary> /// <param name="full"> </param> protected override void Dispose(bool full) { base.Dispose(full); if (null != _package) { _package.Close(); } _package = null; }
private static void CreateManifest(Package package) { using (var writer = XmlWriter.Create(GetPath(PackagePath + "\\" + "AppManifest.xaml"), new XmlWriterSettings { OmitXmlDeclaration = true})) { DeploymentParts.Parent.Save(writer); } CreateManifestPart(package); }
public DocxPackageWriter(Stream stream) { this.package = Package.Open(stream, FileMode.Create); Uri temp = new Uri("/temp.xml", UriKind.Relative); this.package.CreatePart(temp, "application/xml"); this.package.DeletePart(temp); }
public void InitializePackage() { this.outputPackage = Package.Open(this.OutputFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite); this.outputPackage.CreatePart(new Uri("/_index.htm", UriKind.Relative), "text/html"); }
private Package Sign(Package package) { foreach (var packagePart in package.GetParts()) { SignPackagePart(packagePart); } return package; }
public static IEnumerable<PackagePart> GetFooterParts(Package package) { var documentPart = GetDocumentPart(package); var footerRelationships = documentPart.GetRelationshipsByType(FooterRelationshipType); foreach (var relationship in footerRelationships) { yield return package.GetPart(PackUriHelper.ResolvePartUri(documentPart.Uri, relationship.TargetUri)); } }
private static bool CreateRelationshipAndTargetPart( System.IO.Packaging.Package package, System.IO.Packaging.PackagePart sourcePart, string sourceTargetFilePath, string targetUri, string targetMimeType, string relationshipTypeUri) { System.IO.Packaging.PackagePart targetPart; return(CreateRelationshipAndTargetPart( package, sourcePart, sourceTargetFilePath, targetUri, targetMimeType, relationshipTypeUri, out targetPart)); }
public static void AddFile(Package result,string baseFolder,string relativePath,CompressionOption compressionOption) { FileInfo f = new FileInfo(baseFolder+relativePath.Replace("/","\\")); //f.Extension; PackagePart data = result.CreatePart(new Uri(relativePath, UriKind.Relative), GetContentType(f.Name), compressionOption); StreamReader reader = new StreamReader(baseFolder+relativePath.Replace("/","\\")); WriteAll(data.GetStream(), reader.BaseStream); reader.Close(); }
void ExtractContents(Package package, PackageDefinition manifest, string contentNamePrefix, string workingDirectory) { foreach (var namedStreamsContent in manifest.Contents.Where(x => x.Name.StartsWith(contentNamePrefix))) { var destinationFileName = Path.Combine(workingDirectory, ConvertToWindowsPath(namedStreamsContent.Description.DataStorePath.ToString()).TrimStart('\\')); ExtractPart(package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), namedStreamsContent.Description.DataStorePath)), destinationFileName); } }
void AddLocalContent(Package package, PackageDefinition manifest, string workingDirectory) { foreach (var roleDirectory in fileSystem.EnumerateDirectories(Path.Combine(workingDirectory, "LocalContent"))) { var layout = new LayoutDefinition {Name = "Roles/" + new DirectoryInfo(roleDirectory).Name}; manifest.Layouts.Add(layout); AddLocalContentParts(package, manifest, layout, roleDirectory, ""); } }
private static PackagePart GetPackagePart(Package package, string partFilePath) { Uri packagePartUri = GetPackagePartUri(partFilePath); if (package.PartExists(packagePartUri)) return package.GetPart(packagePartUri); else return null; }
private void ReloadZipFile() { Stream s = null; if (_shadowed) { s = new MemoryStream(File.ReadAllBytes(_filename)); } else { s = File.Open(_filename, FileMode.Open, FileAccess.ReadWrite); } _package = Package.Open(s); }
/// <summary> /// Constructor. /// </summary> /// <param name="package">package to filter</param> internal PackageFilter(Package package) { if (package == null) { throw new ArgumentNullException("package"); } _package = package; _partIterator = _package.GetParts().GetEnumerator(); }
private static void CreatePart(Package package, string file, string contentType) { var part = package.CreatePart( new Uri("/" + file, UriKind.Relative), contentType); using (var fileStream = new FileStream( GetPath(PackagePath + file), FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, part.GetStream()); } }
/// <summary> /// Wraps PackWebResponse to ensure correct lifetime handling and stream length functionality /// </summary> /// <param name="s">stream to read from (baseStream)</param> /// <param name="owningStream">stream under the container</param> /// <param name="response">response</param> /// <param name="container">container to hold on to</param> private void Init(Stream s, PackWebResponse response, Stream owningStream, System.IO.Packaging.Package container) { Debug.Assert(s != null, "Logic error: base stream cannot be null"); Debug.Assert(response != null, "Logic error: response cannot be null"); _innerStream = s; _response = response; _owningStream = owningStream; _container = container; }
public ZipArchiveManager(String _path) { // get the stream of the archive // if the file doesn't exits create it this.packageStream = System.IO.File.Open(_path, FileMode.Create); // get the archive // if the archive doesn't exits create it this.package = ZipPackage.Open(packageStream, FileMode.Create); }
private static void AddFileToPackage(Package zip, string f) { PackagePart p = zip.CreatePart( PackUriHelper.CreatePartUri(new Uri(new FileInfo(f).Name, UriKind.RelativeOrAbsolute)), MediaTypeNames.Text.Plain); using (var fileStream = new FileStream(f, FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, p.GetStream()); // zip.CreateRelationship(p.Uri, TargetMode.Internal, f); } }
public static void DoIt() { var uri = new Uri("pack://application:,,,/goof.xps"); var stream = System.Windows.Application.GetResourceStream(uri).Stream; System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(stream); System.IO.Packaging.PackageStore.AddPackage(uri, package); var xpsDoc = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum, uri.AbsoluteUri); var fixedDocumentSequence = xpsDoc.GetFixedDocumentSequence(); }
/// <summary> /// Load all parts /// </summary> private void LoadAll(System.IO.Packaging.Package package) { var sharedObjectCache = new Dictionary <string, byte[]>(); foreach (var part in package.GetParts().Where(x => !IsSharedObject(x.Uri))) { // Load the part's content and store it. var bytes = GetPartContent(package, part, sharedObjectCache); parts[part.Uri] = bytes; } }
private void AddUriToPackage(string path, string file, Package pkg) { Uri uri = null; PackagePart pkgPart = null; uri = PackUriHelper.CreatePartUri(new Uri(file, UriKind.Relative)); pkgPart = pkg.CreatePart(uri, string.Empty); using (FileStream fileStream = new FileStream(path + file, FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, pkgPart.GetStream()); } }
public static PackageDefinition ReadPackageManifest(Package package) { var manifestPart = package.GetPart( package.GetRelationshipsByType(CtpFormatPackageDefinitionRelationshipType).Single().TargetUri); using (var manifestStream = manifestPart.GetStream()) using (var xmlReader = XmlReader.Create(manifestStream, XmlUtils.DtdSafeReaderSettings)) { return new PackageDefinition(XDocument.Load(xmlReader).Root); } }
void AddPackageManifest(Package package, PackageDefinition manifest) { var manifestPartUri = PackUriHelper.CreatePartUri(new Uri("/package.xml", UriKind.Relative)); var manifestPart = package.CreatePart(manifestPartUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum); using (var manifestPartStream = manifestPart.GetStream()) { manifest.ToXml().Save(manifestPartStream); } package.CreateRelationship(manifestPartUri, TargetMode.External, AzureCloudServiceConventions.CtpFormatPackageDefinitionRelationshipType); }
public static XpsDocument FromMemoryStream(System.IO.MemoryStream memoryStream) { string tempPath = "pack://" + Guid.NewGuid().ToString() + ".xps"; System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream); Uri uri = new Uri(tempPath); System.IO.Packaging.PackageStore.AddPackage(uri, package); XpsDocument xpsDocument = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum, tempPath); return(xpsDocument); }
CreateXpsDocument( Stream dataStream ) { Package package = Package.Open(dataStream, FileMode.CreateNew, FileAccess.Write); XpsDocument document = new XpsDocument(package); document.OpcPackage = package; return(document); }
private void LoadEncryptionDetails(System.IO.Packaging.Package package) { var part = package.GetPart(GetUri(EncryptedFile)); var stream = part.GetStream(); JsonSerializer serializer = new JsonSerializer(); #pragma warning disable SG0018 // Path traversal using (var reader = new StreamReader(stream, Encoding.UTF8)) { _encryptionDetails = (EncryptionDetails)serializer.Deserialize(reader, typeof(EncryptionDetails)); } #pragma warning restore SG0018 // Path traversal }
public void Create() { var uri = new Uri("pack://application:,,,/ypi_client_order.xps"); var stream = System.Windows.Application.GetResourceStream(uri).Stream; System.IO.Packaging.Package package1 = System.IO.Packaging.Package.Open(stream); System.IO.Packaging.PackageStore.AddPackage(uri, package1); var xpsDoc = new XpsDocument(package1, System.IO.Packaging.CompressionOption.Maximum, uri.AbsoluteUri); var fixedDocumentSequenceO = xpsDoc.GetFixedDocumentSequence(); MemoryStream xpsStream = new MemoryStream(); Package package2 = Package.Open(xpsStream, FileMode.Create); string memoryStreamUri = "memorystream://printstream"; Uri packageUri = new Uri(memoryStreamUri); PackageStore.AddPackage(packageUri, package2); XpsDocument doc = new XpsDocument(package2, CompressionOption.Fast, memoryStreamUri); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); System.Windows.Documents.Serialization.SerializerWriterCollator vxpsd = writer.CreateVisualsCollator(); int pageno = 1; foreach (System.Windows.Documents.DocumentReference r in fixedDocumentSequenceO.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); //PackageStore.RemovePackage(packageUri); //doc.Close(); } } doc.Close(); xpsStream.Position = 0; Package finalPackage = Package.Open(xpsStream, FileMode.Open); XpsDocument finalDoc = new XpsDocument(finalPackage, CompressionOption.Fast, memoryStreamUri); var fixedDocumentSequence = xpsDoc.GetFixedDocumentSequence(); }
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); }
/// <summary> ///By package because ChangeDocumentType not working well /// </summary> /// <param name="documentStream"></param> private void ChangeDocmToDocxUsingPackage(Stream documentStream) { // Open the document in the stream and replace the custom XML part using (System.IO.Packaging.Package packageFile = System.IO.Packaging.Package.Open(documentStream, FileMode.Open, FileAccess.ReadWrite)) { System.IO.Packaging.PackagePart packagePart = null; // Find part containing the correct namespace foreach (var part in packageFile.GetParts()) { if (part.ContentType.Equals("application/vnd.ms-word.document.macroEnabled.main+xml", StringComparison.OrdinalIgnoreCase)) { packagePart = part; break; } } if (packagePart != null) { using (MemoryStream source = new MemoryStream()) { CopyStream(packagePart.GetStream(), source); var saveRelationBeforeDelPart = new List <PackageRelationship>(); foreach (var item in packagePart.GetRelationships()) { saveRelationBeforeDelPart.Add(item); } Uri uriData = packagePart.Uri; // Delete the existing XML part if (packageFile.PartExists(uriData)) { packageFile.DeletePart(uriData); } // Load the custom XML data var pkgprtData = packageFile.CreatePart(uriData, "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", System.IO.Packaging.CompressionOption.SuperFast); source.Position = 0;//reset position CopyStream(source, pkgprtData.GetStream(FileMode.Create)); foreach (var copyRel in saveRelationBeforeDelPart) { pkgprtData.CreateRelationship(copyRel.TargetUri, copyRel.TargetMode, copyRel.RelationshipType, copyRel.Id); } } } } }
/// <summary> /// Default ctor /// </summary> private Package(System.IO.Packaging.Package package) { if (package != null) { LoadAll(package); } railway = ReadEntity <Railway>(PackageFolders.Railway, RailwayId); if (railway == null) { railway = new Railway(); railway.Package = this; railway.Id = Entity.UniqueId(); var uri = CreatePartUri(railway.PackageFolder, RailwayId); loadedEntities[uri] = railway; } dirty = false; }
private static bool IsEncrypted([NotNull] System.IO.Packaging.Package package) { bool result = false; try { package.GetPart(GetUri(EncryptedFile)); result = true; } #pragma warning disable S2486 // Generic exceptions should not be ignored catch { } #pragma warning restore S2486 // Generic exceptions should not be ignored return(result); }
XpsDocument( Package package, CompressionOption compressionOption, String path ) : base(new XpsManager(package, compressionOption ) ) { if (path != null) { this.Uri = new Uri(path, UriKind.RelativeOrAbsolute); } CurrentXpsManager.XpsDocument = this; Initialize(); }
/// <summary> /// Creates a package-level or part-level relationship and its target part /// (if the target part wasn't already created before). If the sourceTargetFilePath does not exist, /// then both relationship and part will not be created. /// </summary> /// <param name="package"></param> /// <param name="sourcePart">Set to null for a package-level relationship</param> /// <param name="sourceTargetFilePath"></param> /// <param name="targetUri"></param> /// <param name="targetMimeType"></param> /// <param name="relationshipTypeUri"></param> /// <param name="targetPart">The target part that was created</param> /// <returns>True if relationship and part (if not already created before) was created, /// False if source file does not exist and thus relationship and part wasn't created.</returns> private static bool CreateRelationshipAndTargetPart( System.IO.Packaging.Package package, System.IO.Packaging.PackagePart sourcePart, string sourceTargetFilePath, string targetUri, string targetMimeType, string relationshipTypeUri, out System.IO.Packaging.PackagePart targetPart) { // TODO add console output for added parts and relationships targetPart = null; if (!File.Exists(sourceTargetFilePath)) { Console.WriteLine( "Warning: The following source file does not exist: " + sourceTargetFilePath + ". Part and relationship will not be created."); return(false); } try { targetPart = package.CreatePart( PackUriHelper.CreatePartUri( new Uri(targetUri, UriKind.Relative)), targetMimeType, CompressionOption.Maximum); using (FileStream fileStream = new FileStream(sourceTargetFilePath, FileMode.Open, FileAccess.Read)) { fileStream.CopyTo(targetPart.GetStream()); } } catch (InvalidOperationException) { Console.WriteLine( "Warning: The following part URI already exists and will not be created again: " + targetUri + ". Relationship will still be created."); } if (sourcePart == null) { package.CreateRelationship( PackUriHelper.CreatePartUri( new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri); } else { sourcePart.CreateRelationship( PackUriHelper.CreatePartUri( new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri); } return(true); }
CreateXpsDocument( Stream dataStream ) { // In .NET Core 3.0 System.IO.Compression's ZipArchive does not allow creation of ZipArchiveEntries when // a prior ZipArchiveEntry is still open. XPS Serialization requires this as part of its implementation. // To get around this, XPS creation should occur in with FileAccess.ReadWrite if the underlying stream // supports it. This allows multiple ZipArchiveEntries to be open concurrently. Package package = Package.Open(dataStream, FileMode.CreateNew, (dataStream.CanRead) ? FileAccess.ReadWrite : FileAccess.Write); XpsDocument document = new XpsDocument(package); document.OpcPackage = package; return(document); }
public void Zip(string fullPathSource, bool recursive, string whereClause, string fullPathDestination, string zipFileName, bool overWrite) { Log.WriteLog(" -- Init -- ", "Log", this.GetType().Name, this.AppConfig); List <FileInfo> selectedFiles = this.SelectFiles(fullPathSource, recursive, whereClause, fullPathDestination); if (File.Exists(string.Concat(fullPathDestination, "\\", zipFileName)) && overWrite) { File.Delete(string.Concat(fullPathDestination, "\\", zipFileName)); } else if (File.Exists(string.Concat(fullPathDestination, "\\", zipFileName))) { throw new IOException("File already exists"); } string location = string.Concat(fullPathDestination, "\\", zipFileName); if (Path.GetExtension(location).ToLower() != ".zip") { throw new IOException("File Extension in not valid"); } FileStream ZipFileStream = new FileStream(location, FileMode.Create); using (System.IO.Packaging.Package Package = System.IO.Packaging.Package.Open(ZipFileStream, FileMode.OpenOrCreate)) { foreach (FileInfo file in selectedFiles) { try { string[] strArrays = new string[] { string.Concat(this.RemoveDrivefromDirectory(file.DirectoryName), "\\", file.Name) }; Uri UriPath = PackUriHelper.CreatePartUri(new Uri(Path.Combine(strArrays), UriKind.Relative)); System.IO.Packaging.PackagePart PackagePart = Package.CreatePart(UriPath, "text/xml", CompressionOption.Maximum); string[] strArrays1 = new string[] { string.Concat(file.DirectoryName, "\\", file.Name) }; byte[] Data = File.ReadAllBytes(Path.Combine(strArrays1)); PackagePart.GetStream().Write(Data, 0, Data.Count <byte>()); Package.CreateRelationship(PackagePart.Uri, TargetMode.Internal, "http://schemas.microsoft.com/opc/2006/sample/document"); } catch (Exception exception) { Exception e = exception; Log.WriteLog(e.Message, "Error", this.GetType().Name, this.AppConfig); throw e; } } } ZipFileStream.Close(); }
public void SaveAsXps(string fileName, FlowDocument document) { using (System.IO.Packaging.Package container = System.IO.Packaging.Package.Open(fileName, FileMode.Create)) { using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum)) { XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false); DocumentPaginator paginator = ((IDocumentPaginatorSource)document).DocumentPaginator; //16.5=6.4960=623.616 //11=4.3307=415.74 paginator = new DocumentPaginatorWrapper(paginator, new Size(416, 624), new Size(15, 15)); rsm.SaveAsXaml(paginator); } } }
AddThumbnail( XpsImageType imageType ) { CheckDisposed(); if (CurrentXpsManager == null) { throw new InvalidOperationException(SR.Get(SRID.ReachPackaging_DocumentWasClosed)); } _thumbnail = CurrentXpsManager.AddThumbnail(imageType, this, Thumbnail); Package metroPackage = CurrentXpsManager.MetroPackage; metroPackage.CreateRelationship(_thumbnail.Uri, TargetMode.Internal, XpsS0Markup.ThumbnailRelationshipName ); return(_thumbnail); }
/// <summary> /// Creates a new instance of the WordprocessingDocument class from the spcified package. /// </summary> /// <param name="package">The specified OpenXml package</param> /// <param name="openSettings">The advanced settings for opening a document.</param> /// <returns>A new instance of WordprocessingDocument.</returns> /// <exception cref="ArgumentNullException">Thrown when package is a null reference.</exception> /// <exception cref="OpenXmlPackageException">Thrown when package is not opened with read access.</exception> /// <exception cref="OpenXmlPackageException">Thrown when the package is not a valid Open XML document.</exception> /// <exception cref="ArgumentException">Thrown when specified to process the markup compatibility but the given target FileFormatVersion is incorrect.</exception> public static WordprocessingDocument Open(System.IO.Packaging.Package package, OpenSettings openSettings) { if (openSettings.MarkupCompatibilityProcessSettings.ProcessMode != MarkupCompatibilityProcessMode.NoProcess && !openSettings.MarkupCompatibilityProcessSettings.TargetFileFormatVersions.Any()) { throw new ArgumentException(ExceptionMessages.InvalidMCMode); } WordprocessingDocument doc = new WordprocessingDocument(); doc.OpenSettings = new OpenSettings(); doc.OpenSettings.AutoSave = openSettings.AutoSave; doc.OpenSettings.MarkupCompatibilityProcessSettings.ProcessMode = openSettings.MarkupCompatibilityProcessSettings.ProcessMode; doc.OpenSettings.MarkupCompatibilityProcessSettings.TargetFileFormatVersions = openSettings.MarkupCompatibilityProcessSettings.TargetFileFormatVersions; doc.MaxCharactersInPart = openSettings.MaxCharactersInPart; doc.OpenCore(package); if (MainPartContentTypes[doc.DocumentType] != doc.MainPartContentType) { doc.UpdateDocumentTypeFromContentType(); } return(doc); }
/// <summary> /// Gets the content of the given part. /// Shared objects are resolved here. /// </summary> private static byte[] GetPartContent(System.IO.Packaging.Package package, PackagePart part, Dictionary <string, byte[]> sharedObjectCache) { // Check type of part and load content according to this type. if (part.ContentType == ContentTypeSharedObject) { // Content is stored in a shared object var hash = Hex(ToArray(part.GetStream())); byte[] bytes; if (sharedObjectCache.TryGetValue(hash, out bytes)) { return(bytes); } var objectPart = package.GetPart(CreateSharedObjectPartUri(hash)); bytes = ToArray(objectPart.GetStream(FileMode.Open)); sharedObjectCache[hash] = bytes; return(bytes); } // Content is stored unshared return(ToArray(part.GetStream(FileMode.Open))); }
/// <summary> /// Gets the content of the given part. /// Shared objects are resolved here. /// </summary> private static void SavePartContent(System.IO.Packaging.Package package, Uri uri, byte[] content, Dictionary <string, string> sharedObjects) { // Decide how to store this content if (content.Length < 80) { // Store directly var contentPart = package.CreatePart(uri, ContentTypeZip, CompressionOption.Normal); using (var contentPartStream = contentPart.GetStream(FileMode.Create, FileAccess.Write)) { contentPartStream.Write(content, 0, content.Length); } } else { // Store as shared object var hash = CreateHash(content); var hashKey = Hex(hash); // Create content part that contains the hash of the shared object. var contentPart = package.CreatePart(uri, ContentTypeSharedObject, CompressionOption.NotCompressed); using (var contentPartStream = contentPart.GetStream(FileMode.Create, FileAccess.Write)) { contentPartStream.Write(hash, 0, hash.Length); } // Does the shared object exists? if (!sharedObjects.ContainsKey(hashKey)) { // Create shared object part var sharedObjectUri = CreateSharedObjectPartUri(hashKey); var objectPart = package.CreatePart(sharedObjectUri, ContentTypeZip, CompressionOption.Normal); using (var objectPartStream = objectPart.GetStream(FileMode.Create, FileAccess.Write)) { objectPartStream.Write(content, 0, content.Length); } sharedObjects[hashKey] = hashKey; } } }
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); } }
public static SpreadsheetDocument Open(System.IO.Packaging.Package package) { return(SpreadsheetDocument.Open(package, new OpenSettings())); }
/// <summary> /// Creates a new instance of the PresentationDocument class from the spcified package. /// </summary> /// <param name="package">The specified OpenXml package.</param> /// <returns>A new instance of PresentationDocument.</returns> /// <exception cref="ArgumentNullException">Thrown when "package" is null reference.</exception> /// <exception cref="IOException">Thrown when "package" is not opened with Read (ReadWrite) access.</exception> /// <exception cref="OpenXmlPackageException">Thrown when the package is not valid Open XML PresentationDocument.</exception> public static PresentationDocument Open(System.IO.Packaging.Package package) { return(PresentationDocument.Open(package, new OpenSettings())); }
XpsDocument( Package package ) : this(package, CompressionOption.Maximum) { }
/// <summary> /// Creates a new instance of the WordprocessingDocument class from the spcified package. /// </summary> /// <param name="package">The specified OpenXml package.</param> /// <returns>A new instance of WordprocessingDocument.</returns> /// <exception cref="ArgumentNullException">Thrown when "package" is null reference.</exception> /// <exception cref="IOException">Thrown when "package" is not opened with Read (ReadWrite) access.</exception> /// <exception cref="OpenXmlPackageException">Thrown when the package is not valid Open XML WordprocessingDocument.</exception> public static WordprocessingDocument Open(System.IO.Packaging.Package package) { return(WordprocessingDocument.Open(package, new OpenSettings())); }