Exemple #1
0
        public static invoice MapToInvoice(string xml)
        {
            var    p            = new Saxon.Api.Processor();
            var    c            = p.NewXsltCompiler();
            string rootNodeName = XDocument.Load(xml).Root.Name.LocalName;

            Saxon.Api.XsltExecutable ex;
            if (rootNodeName == "Invoice")
            {
                ex = c.Compile(GenerateStreamFromString(Properties.Resources.ubl_invoice_xr));
            }
            else if (rootNodeName == "CrossIndustryInvoice")
            {
                ex = c.Compile(GenerateStreamFromString(Properties.Resources.cii_xr));
            }
            else
            {
                return(null);
            }
            var transformer = ex.Load();

            transformer.SetInputStream(File.OpenRead(xml), new Uri(@"C:\")); //TODO Temp URI
            var destination = new Saxon.Api.DomDestination();

            transformer.Run(destination);
            var ms = new MemoryStream();

            destination.XmlDocument.Save(ms);
            ms.Flush();
            ms.Position = 0;
            var s = new XmlSerializer(typeof(invoice));

            return((invoice)s.Deserialize(ms));
        }
Exemple #2
0
        public AboutForm()
        {
            InitializeComponent();
            this.linkLabel1.Links.Add(68, 5, "http://www.saxonica.com");
            this.linkLabel1.Links.Add(78, 12, "https://github.com/jacobslusser/ScintillaNET");
            this.linkLabel1.LinkClicked += new LinkLabelLinkClickedEventHandler(linkLabelClicked);
            string saxonVersion = new Saxon.Api.Processor().ProductVersion;

            this.linkLabel1.Text += saxonVersion;
            this.linkLabel1.Text += "\r\nBuild: " + System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString(" yyyyMMddHH");
        }
Exemple #3
0
        private string TransformRecord(string stext, string sXSLT)
        {
            //use Saxon; which will be installed with MarcEdit; to allow xslt 1, 2, and 3

            System.IO.StringReader sreader      = new System.IO.StringReader(stext);
            System.Xml.XmlReader   xreader      = System.Xml.XmlReader.Create(sreader);
            Saxon.Api.Processor    processor    = new Saxon.Api.Processor();
            Saxon.Api.XsltCompiler xsltCompiler = processor.NewXsltCompiler();
            Saxon.Api.XdmNode      input        = processor.NewDocumentBuilder().Build(xreader);


            // Create a transformer for the stylesheet.
            Saxon.Api.XsltTransformer transformer = null;
            if (System.IO.File.Exists(sXSLT))
            {
                System.IO.FileStream xstream = new System.IO.FileStream(sXSLT, System.IO.FileMode.Open);
                xsltCompiler.BaseUri = new Uri(System.IO.Path.GetDirectoryName(sXSLT) + System.IO.Path.DirectorySeparatorChar.ToString(), UriKind.Absolute);
                transformer          = xsltCompiler.Compile(xstream).Load();
            }
            else
            {
                lbStatus.Text = "ERROR applying the cutom rules file";
                return("");
            }



            // Set the root node of the source document to be the initial context node
            transformer.InitialContextNode = input;

            // Create a serializer
            Saxon.Api.Serializer serializer   = new Saxon.Api.Serializer();
            System.IO.TextWriter stringWriter = new System.IO.StringWriter();
            serializer.SetOutputWriter(stringWriter);
            transformer.Run(serializer);

            string tmp = stringWriter.ToString();

            //System.Windows.Forms.MessageBox.Show(tmp);
            //****Remove these lines because all the white space was being removed on translation***
            //System.Text.RegularExpressions.Regex objRegEx = new System.Text.RegularExpressions.Regex(@"\n +=LDR ", System.Text.RegularExpressions.RegexOptions.None);
            //tmp = objRegEx.Replace(tmp, "\n" + @"=LDR ");

            return(tmp);
        }
Exemple #4
0
        public string Transform(Stream XMLStream, Stream xsltStream)
        {
            // Compile stylesheet

            var processor  = new Saxon.Api.Processor();
            var compiler   = processor.NewXsltCompiler();
            var executable = compiler.Compile(xsltStream);

            // Do transformation to a destination
            var destination = new Saxon.Api.DomDestination();

            // using (var inputStream = input.OpenRead())
            {
                var transformer = executable.Load();
                transformer.SetInputStream(XMLStream, new Uri("http://www.w3.org/"));
                transformer.Run(destination);
            }

            // Save result to a file (or whatever else you wanna do)
            // destination.XmlDocument.Save(output.FullName);
            return(destination.XmlDocument.OuterXml);
        }
Exemple #5
0
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            return(inputs.AsParallel().Select(context, input =>
            {
                try
                {
                    Saxon.Api.Processor processor = new Saxon.Api.Processor();
                    Saxon.Api.XsltCompiler xslt = processor.NewXsltCompiler();
                    Saxon.Api.XsltTransformer transformer;
                    if (_xsltPath != null)
                    {
                        FilePath path = _xsltPath.Invoke <FilePath>(input, context);
                        if (path != null)
                        {
                            IFile file = context.FileSystem.GetInputFile(path);
                            if (file.Exists)
                            {
                                using (Stream fileStream = file.OpenRead())
                                {
                                    transformer = LoadXsltDataInTransformer(xslt, fileStream);
                                }
                            }
                            else
                            {
                                throw new FileNotFoundException("Couldn't find XSLT file", file.ToString());
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException("Provided file path was not valid");
                        }
                    }
                    else if (_xsltGeneration != null)
                    {
                        IDocument xsltDocument = context.Execute(_xsltGeneration, new[] { input }).Single();
                        using (Stream stream = xsltDocument.GetStream())
                        {
                            transformer = LoadXsltDataInTransformer(xslt, stream);
                        }
                    }
                    else
                    {
                        //Should never happen, because of null check in Constructor.
                        throw new InvalidOperationException();
                    }

                    using (Stream stream = input.GetStream())
                    {
                        XmlReader xml = XmlReader.Create(stream);

                        Saxon.Api.DocumentBuilder documentBuilder = processor.NewDocumentBuilder();
                        documentBuilder.BaseUri = xslt.BaseUri;
                        Saxon.Api.XdmNode xdmNode = documentBuilder.Build(xml);
                        transformer.InitialContextNode = xdmNode;

                        using (System.IO.StringWriter writer = new StringWriter())
                        {
                            Saxon.Api.Serializer serializer = new Saxon.Api.Serializer();
                            serializer.SetOutputWriter(writer);
                            transformer.Run(serializer);
                            return context.GetDocument(input, writer.ToString());
                        }
                    }
                }
                catch (Exception e)
                {
                    Trace.Error($"An {e.GetType().Name} occurred: {e.Message}");
                    return null;
                }
            }).Where(x => x != null));
        }
Exemple #6
0
        public Файл ВыводОтчета(string НазваниеОтчета, string ИсходныйКод, string ИсходныйФорматОтчета, ФорматОтчета ФорматОтчета, ШаблонОтчета.Ориентация Ориентация, DataSet ds, Хранилище Хранилище, string user, string domain)
        {
            var file = null as Файл;

            try
            {
                if (ds == null)
                {
                    new Exception("Не определен DataSet");
                }

                var extension = string.Empty;
                var mime      = MimeType.НеОпределен;
                switch (ИсходныйФорматОтчета)
                {
                case "Xps":
                    extension = "xps";
                    mime      = MimeType.Xps;
                    break;

                case "Excel":
                    extension = "xls";
                    mime      = MimeType.Excel;
                    break;

                case "Word":
                    extension = "doc";
                    mime      = MimeType.Word;
                    break;

                case "Text Plain":
                    extension = "txt";
                    mime      = MimeType.Text;
                    break;

                case "Excel-PDF":
                case "Word-PDF":
                    extension = "pdf";
                    break;

                default:
                    throw new Exception("Не верно указан 'Исходный формат отчета'");
                }
                file = new Файл()
                {
                    Name = string.Format("{0}_{1:yyyymmdd_HHmmss}.{2}", FileNameValid(НазваниеОтчета), DateTime.Now, extension), MimeType = mime
                };
                var task = new System.Threading.Tasks.Task(() =>
                {
                    try
                    {
                        using (var msXml = new MemoryStream())
                        {
                            var processor   = new Saxon.Api.Processor();
                            var compiler    = processor.NewXsltCompiler();
                            var transformer = compiler.Compile(new StringReader(ИсходныйКод)).Load();
                            var dest        = new Saxon.Api.TextWriterDestination(XmlTextWriter.Create(msXml));

                            transformer.InitialContextNode = processor.NewDocumentBuilder().Build(new XmlDataDocument(ds));
                            transformer.Run(dest);

                            switch (ИсходныйФорматОтчета)
                            {
                            case "Xps":
                                {
                                    file.MimeType = MimeType.Xps;
                                    switch (ФорматОтчета)
                                    {
                                        #region Отчет Xaml (по-умолчанию)
                                    case ФорматОтчета.Xaml:
                                    case ФорматОтчета.ПоУмолчанию:
                                        {
                                            file.Stream = msXml.ToArray();
                                        }
                                        break;
                                        #endregion

                                        #region Отчет Xps
                                    case ФорматОтчета.Xps:
                                    default:
                                        {
                                            var documentUri = Path.GetTempFileName();
                                            try
                                            {
                                                msXml.Position = 0;
                                                var sourceDoc  = XamlReader.Load(msXml) as IDocumentPaginatorSource;

                                                var doc = new XpsDocument(documentUri, FileAccess.Write, CompressionOption.Normal);
                                                var xsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
                                                var pgn = sourceDoc.DocumentPaginator;
                                                // 1cm = 38px
                                                switch (Ориентация)
                                                {
                                                case ШаблонОтчета.Ориентация.Альбом:
                                                    {
                                                        pgn.PageSize = new System.Windows.Size(29.7 * (96 / 2.54), 21 * (96 / 2.54));
                                                    }
                                                    break;

                                                case ШаблонОтчета.Ориентация.Книга:
                                                default:
                                                    {
                                                        pgn.PageSize = new System.Windows.Size(21 * (96 / 2.54), 29.7 * (96 / 2.54));
                                                    }
                                                    break;
                                                }
                                                //необходимо фиксированно указать размер колонки документа иначе при
                                                //построении часть данных будет срезано
                                                if (sourceDoc is FlowDocument)
                                                {
                                                    ((FlowDocument)sourceDoc).ColumnWidth = pgn.PageSize.Width;
                                                }
                                                xsm.SaveAsXaml(pgn);

                                                doc.Close();
                                                file.Stream = System.IO.File.ReadAllBytes(documentUri);
                                            }
                                            finally
                                            {
                                                if (System.IO.File.Exists(documentUri))
                                                {
                                                    System.IO.File.Delete(documentUri);
                                                }
                                            }
                                        }
                                        break;
                                        #endregion
                                    }
                                }
                                break;

                            case "TextPlain":
                                {
                                    file.MimeType = MimeType.Text;
                                    file.Stream   = msXml.ToArray();
                                }
                                break;

                            case "Word-PDF":
                                {
                                    #region generate
                                    object paramSourceDocPath = Path.GetTempFileName();
                                    object paramMissing       = System.Type.Missing;

                                    System.IO.File.WriteAllBytes((string)paramSourceDocPath, msXml.ToArray());
                                    if (!System.IO.File.Exists((string)paramSourceDocPath))
                                    {
                                        throw new Exception(string.Format("Исходный файл для генерации отчета не найден '{0}'", paramSourceDocPath));
                                    }

                                    var wordApplication     = null as Microsoft.Office.Interop.Word.Application;
                                    var wordDocument        = null as Document;
                                    var paramExportFilePath = GetTempFilePathWithExtension(".pdf");
                                    try
                                    {
                                        wordApplication = new Microsoft.Office.Interop.Word.Application()
                                        {
                                            DisplayAlerts = WdAlertLevel.wdAlertsNone
                                        };

                                        var paramExportFormat       = WdExportFormat.wdExportFormatPDF;
                                        var paramOpenAfterExport    = false;
                                        var paramExportOptimizeFor  = WdExportOptimizeFor.wdExportOptimizeForPrint;
                                        var paramExportRange        = WdExportRange.wdExportAllDocument;
                                        var paramStartPage          = 0;
                                        var paramEndPage            = 0;
                                        var paramExportItem         = WdExportItem.wdExportDocumentContent;
                                        var paramIncludeDocProps    = true;
                                        var paramKeepIRM            = true;
                                        var paramCreateBookmarks    = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                                        var paramDocStructureTags   = true;
                                        var paramBitmapMissingFonts = true;
                                        var paramUseISO19005_1      = false;

                                        // Open the source document.
                                        wordDocument = wordApplication.Documents.Open(
                                            ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing);

                                        // Export it in the specified format.
                                        if (wordDocument != null)
                                        {
                                            wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                                             paramExportFormat, paramOpenAfterExport,
                                                                             paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                                             paramEndPage, paramExportItem, paramIncludeDocProps,
                                                                             paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                                             paramBitmapMissingFonts, paramUseISO19005_1,
                                                                             ref paramMissing);
                                        }

                                        if (!System.IO.File.Exists(paramExportFilePath))
                                        {
                                            throw new Exception(string.Format("Word-PDF: Файл отчета не найден '{0}'", paramExportFilePath));
                                        }

                                        if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                        {
                                            file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                        }

                                        file.Stream = System.IO.File.ReadAllBytes(paramExportFilePath);
                                    }
                                    finally
                                    {
                                        // Close and release the Document object.
                                        if (wordDocument != null)
                                        {
                                            wordDocument.Close(false, ref paramMissing, ref paramMissing);
                                            wordDocument = null;
                                        }

                                        // Quit Word and release the ApplicationClass object.
                                        if (wordApplication != null)
                                        {
                                            wordApplication.Quit(false, ref paramMissing, ref paramMissing);
                                            wordApplication = null;

                                            GC.Collect();
                                            GC.WaitForPendingFinalizers();
                                            GC.Collect();
                                        }

                                        if (System.IO.File.Exists((string)paramSourceDocPath))
                                        {
                                            System.IO.File.Delete((string)paramSourceDocPath);
                                        }
                                        if (System.IO.File.Exists(paramExportFilePath))
                                        {
                                            System.IO.File.Delete(paramExportFilePath);
                                        }

                                        //var sb = new StringBuilder();
                                        //sb.AppendLine((string)paramSourceDocPath);
                                        //sb.AppendLine(paramExportFilePath);
                                        //ConfigurationClient.WindowsLog(sb.ToString(), "", domain);
                                    }
                                    #endregion
                                }
                                break;

                            case "Excel-PDF":
                                {
                                    #region generate
                                    object paramSourceDocPath = Path.GetTempFileName();
                                    object paramMissing       = System.Type.Missing;

                                    System.IO.File.WriteAllBytes((string)paramSourceDocPath, msXml.ToArray());
                                    if (!System.IO.File.Exists((string)paramSourceDocPath))
                                    {
                                        throw new Exception(string.Format("Исходный файл для генерации отчета не найден '{0}'", paramSourceDocPath));
                                    }

                                    var excelApplication = new Microsoft.Office.Interop.Excel.Application()
                                    {
                                        DisplayAlerts = false
                                    };
                                    var excelDocument = null as Workbook;

                                    var paramExportFilePath   = GetTempFilePathWithExtension(".pdf");
                                    var paramExportFormat     = XlFixedFormatType.xlTypePDF;
                                    var paramExportQuality    = XlFixedFormatQuality.xlQualityStandard;
                                    var paramOpenAfterPublish = false;
                                    var paramIncludeDocProps  = true;
                                    var paramIgnorePrintAreas = true;
                                    var paramFromPage         = System.Type.Missing;
                                    var paramToPage           = System.Type.Missing;

                                    try
                                    {
                                        // Open the source document.
                                        excelDocument = excelApplication.Workbooks.Open(
                                            (string)paramSourceDocPath, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing);

                                        // Export it in the specified format.
                                        if (excelDocument != null)
                                        {
                                            excelDocument.ExportAsFixedFormat(paramExportFormat,
                                                                              paramExportFilePath, paramExportQuality,
                                                                              paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage,
                                                                              paramToPage, paramOpenAfterPublish,
                                                                              paramMissing);
                                        }

                                        if (!System.IO.File.Exists(paramExportFilePath))
                                        {
                                            throw new Exception(string.Format("Файл отчета не найден '{0}'", paramExportFilePath));
                                        }

                                        if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                        {
                                            file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                        }

                                        file.Stream = System.IO.File.ReadAllBytes(paramExportFilePath);
                                    }
                                    finally
                                    {
                                        // Close and release the Document object.
                                        if (excelDocument != null)
                                        {
                                            excelDocument.Close(false, paramMissing, paramMissing);
                                            excelDocument = null;
                                        }

                                        // Quit Word and release the ApplicationClass object.
                                        if (excelApplication != null)
                                        {
                                            excelApplication.Quit();
                                            excelApplication = null;
                                        }

                                        if (System.IO.File.Exists((string)paramSourceDocPath))
                                        {
                                            System.IO.File.Delete((string)paramSourceDocPath);
                                        }
                                        if (System.IO.File.Exists(paramExportFilePath))
                                        {
                                            System.IO.File.Delete(paramExportFilePath);
                                        }

                                        GC.Collect();
                                        GC.WaitForPendingFinalizers();
                                        GC.Collect();
                                        GC.WaitForPendingFinalizers();
                                    }
                                    #endregion
                                }
                                break;

                            default:
                                {
                                    if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                    {
                                        file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                    }

                                    file.Stream = msXml.ToArray();
                                }
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ConfigurationClient.WindowsLog(ex.ToString(), user, domain, "ВыводОтчета");
                    }
                });
                task.Start();
                task.Wait();
            }
            catch (Exception ex)
            {
                ConfigurationClient.WindowsLog(ex.ToString(), user, domain, "ВыводОтчета");
            }
            return(file);
        }