Esempio n. 1
2
        static void Main(string[] args)
        {
            const string filename = "test.docx";
            string html = Demo.Properties.Resources.CompleteRunTest;
            if (File.Exists(filename)) File.Delete(filename);

            using (MemoryStream generatedDocument = new MemoryStream())
            {
                // Uncomment and comment the second using() to open an existing template document
                // instead of creating it from scratch.

                byte[] data = Demo.Properties.Resources.template;
                generatedDocument.Write(data, 0, data.Length);
                generatedDocument.Position = 0L;
                using (WordprocessingDocument package = WordprocessingDocument.Open(generatedDocument, true))
                //using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                {
                    MainDocumentPart mainPart = package.MainDocumentPart;
                    if (mainPart == null)
                    {
                        mainPart = package.AddMainDocumentPart();
                        new Document(new Body()).Save(mainPart);
                    }

                    HtmlConverter converter = new HtmlConverter(mainPart);
                    //converter.WebProxy.Credentials = new System.Net.NetworkCredential("nizeto", "****", "domain");
                    //converter.WebProxy.Proxy = new System.Net.WebProxy("proxy01:8080");
                    converter.ImageProcessing = ImageProcessing.ManualProvisioning;
                    converter.ProvisionImage += OnProvisionImage;

                    Body body = mainPart.Document.Body;

                    converter.ParseHtml(html);
                    mainPart.Document.Save();

                    //AssertThatOpenXmlDocumentIsValid(package);
                }

                File.WriteAllBytes(filename, generatedDocument.ToArray());
            }

            System.Diagnostics.Process.Start(filename);
        }
        // Creates an TableRow instance and adds its children.
        public TableRow GenerateTableRow_Corpo(string PathImage,string Codice,string descrizione,string SpecificheTecniche,string Importo)
        {
            TableRow tableRow1 = new TableRow() { RsidTableRowAddition = "005B040A", RsidTableRowProperties = "005B040A" };

            TableCell tableCellImmagine = new TableCell();
            tableCellImmagine.Append(GenerateTableCellProperties_Corpo());
            tableCellImmagine.Append(ImageGest.AddImageParagraph(_MainPart, PathImage,Codice + "Immagine"));

            TableCell tableCellDescrizione = new TableCell();

            tableCellDescrizione.Append(GenerateTableCellProperties_Corpo());
            tableCellDescrizione.Append(GenerateParagraphCellDesCodice(Codice));

            HtmlConverter converter = new HtmlConverter(_MainPart);


            var par1 = converter.Parse(descrizione);
            for (int i = 0; i < par1.Count; i++)
            {
                tableCellDescrizione.Append((par1[i]));
            }
            var par2 = converter.Parse(SpecificheTecniche);
            for (int i = 0; i < par2.Count; i++)
            {
                tableCellDescrizione.Append((par2[i]));
            }

            //tableCellDescrizione.Append(GenerateParagraphCellDesDescrizione(descrizione));
            //tableCellDescrizione.Append(GenerateParagraphCellDesSpecificheTecniche(SpecificheTecniche));

            TableCell tableCellImporto = new TableCell();

            tableCellImporto.Append(GenerateTableCellProperties_Corpo());
            tableCellImporto.Append(GenerateParagraphCellImporto(Importo));

            tableRow1.Append(GenerateTableRowProperties_Titolo());
            tableRow1.Append(tableCellImmagine);
            tableRow1.Append(tableCellDescrizione);
            tableRow1.Append(tableCellImporto);

            return tableRow1;
        }
Esempio n. 3
2
        private IList<OpenXmlCompositeElement> CreateOpenXmlParagraphs(MainDocumentPart mainDocumentPart)
        {
            var converter = new HtmlConverter(mainDocumentPart);
            converter.HtmlStyles.StyleMissing += (sender, args) =>
                {
                    Debug.WriteLine(String.Format("Style is missing: {0}", args.Name));
                };
            converter.ConsiderDivAsParagraph = true;

            var list = converter.Parse(HtmlString);
            foreach (OpenXmlCompositeElement item in list)
            {
                var numberingProperties = item.Descendants<NumberingProperties>().FirstOrDefault();
                if (numberingProperties == null)
                    continue;

                var paragraphProperties = numberingProperties.Parent as ParagraphProperties;
                paragraphProperties.ParagraphStyleId = new ParagraphStyleId { Val = "BulletList" };

                numberingProperties.Remove();
                paragraphProperties.GetFirstChild<SpacingBetweenLines>().Remove();
            }

            return list;
        }
Esempio n. 4
1
 private IList<OpenXmlCompositeElement> ConvertContentToParagraphs(MainDocumentPart mainDocumentPart)
 {
     var converter = new HtmlConverter(mainDocumentPart) { RenderPreAsTable = false };
     return converter.Parse(_content
         .Replace("<img", "<img style=\"max-width:550;\"")
         .Replace("<pre><code>", "<p class=\"codesnippet\"><pre>")
         .Replace("</code></pre>", "</pre></p>")
         .Replace("<code>", "<span class=\"inlinecodesnippet\">")
         .Replace("</code>", "</span>"));
 }
        private static byte[] GenerateDocument(string data)
        {
            byte[] document;
            using (var generatedDocument = new MemoryStream())
            {
                using (var package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                {
                    var mainPart = package.MainDocumentPart;
                    if (mainPart == null)
                    {
                        mainPart = package.AddMainDocumentPart();
                        new Document(new Body()).Save(mainPart);
                    }

                    var converter = new HtmlConverter(mainPart);
                    var body = mainPart.Document.Body;

                    var paragraphs = converter.Parse(data);
                    foreach (var t in paragraphs)
                    {
                        body.Append(t);
                    }

                    mainPart.Document.Save();
                }

                document = generatedDocument.ToArray();
            }

            return document;
        }
        public void generateReport(String filename, String html, bool landscape, bool fiveByEight)
        {
            try
            {
                string contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                using (MemoryStream generatedDocument = new MemoryStream())
                {
                    using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                    {
                        MainDocumentPart mainPart = package.MainDocumentPart;
                        if (mainPart == null)
                        {
                            mainPart = package.AddMainDocumentPart();
                            new Document(new Body()).Save(mainPart);
                        }

                        HtmlConverter converter = new HtmlConverter(mainPart);

                        //http://html2openxml.codeplex.com/wikipage?title=ImageProcessing&referringTitle=Documentation
                        //to process an image you must provide a base

                        //Uri baseImageUrl = new Uri(Request.Url.Scheme + "://" + Request.Url.Authority);
                        //converter.BaseImageUrl = baseImageUrl;
                        // Test

                        Body body = mainPart.Document.Body;

                        if (landscape)
                        {
                            SectionProperties properties = new SectionProperties();
                            PageSize pageSize;

                            if (fiveByEight)
                            {
                                pageSize = new PageSize()
                                {
                                    Width = (UInt32Value)11520U,
                                    Height = (UInt32Value)7200U,
                                    Orient = PageOrientationValues.Landscape
                                };
                            }
                            else
                            {
                                pageSize = new PageSize()
                                {
                                    Width = (UInt32Value)15840U,
                                    Height = (UInt32Value)12240U,
                                    Orient = PageOrientationValues.Landscape
                                };
                            }
                            properties.Append(pageSize);

                            PageMargin pageMargin = new PageMargin()
                            {
                                Top = 720,
                                Right = (UInt32Value)1008U,
                                Bottom = 720,
                                Left = (UInt32Value)1008U,
                                Header = (UInt32Value)720U,
                                Footer = (UInt32Value)720U,
                                Gutter = (UInt32Value)0U };
                            properties.Append(pageMargin);

                            body.Append(properties);

                            SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };
                            ParagraphProperties paragraphProperties = new ParagraphProperties();
                            Paragraph paragraph = new Paragraph();

                            paragraphProperties.Append(spacing);
                            paragraph.Append(paragraphProperties);
                            body.Append(paragraph);
                        }

                        var paragraphs = converter.Parse(html);
                        for (int i = 0; i < paragraphs.Count; i++)
                        {

                            if (landscape)
                            {
                                ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                                  new ParagraphStyleId() { Val = "No Spacing" },
                                  new SpacingBetweenLines() { After = "0" }
                                 );
                                paragraphs[i].PrependChild(paragraphProperties1);

                            }
                            ParagraphProperties paragraphProperties2 = new ParagraphProperties();
                            ContextualSpacing contextualSpacing = new ContextualSpacing();

                            paragraphProperties2.Append(contextualSpacing);
                            paragraphs[i].Append(paragraphProperties2);
                            body.Append(paragraphs[i]);
                        }

                        //I have no idea why it doesnt work when you try to use pageBreakParagraph... but it doesnt... so redeclare this same string here
                        string lineBreakCharacter = "%$%lineBreak%$%";

                        List<Paragraph> pageBreakMarkers = new List<Paragraph>();
                        var lastP = mainPart.Document.Descendants<Paragraph>().LastOrDefault();
                        foreach (Paragraph P in mainPart.Document.Descendants<Paragraph>())
                        {
                            foreach (Run R in P.Descendants<Run>())
                            {
                                if (R.Descendants<Text>()
                                    .Where(T => T.Text == lineBreakCharacter).Count() > 0)
                                {
                                    if (P != lastP)
                                    {
                                        P.InsertAfterSelf
                                            (new Paragraph(
                                                new Run(
                                                    new Break() { Type = BreakValues.Page })));
                                    }
                                    pageBreakMarkers.Add(P);
                                }
                            }
                        }
                        foreach(Paragraph P in pageBreakMarkers)
                        {
                            P.Remove();
                        }

                        var tables = mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Table>();

                        var last = tables.LastOrDefault();
                        foreach (DocumentFormat.OpenXml.Wordprocessing.Table table in tables)
                        {
                            foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph p in table.Elements<Paragraph>())
                            {
                                ParagraphProperties spaceProperties = new ParagraphProperties();
                                ContextualSpacing contextualSpacing = new ContextualSpacing();

                                spaceProperties.Append(contextualSpacing);
                                p.PrependChild(spaceProperties);
                            }
                            foreach (DocumentFormat.OpenXml.Wordprocessing.TableRow row in table.Elements<DocumentFormat.OpenXml.Wordprocessing.TableRow>())
                            {
                                foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph p in row.Elements<Paragraph>())
                                {
                                    ParagraphProperties spaceProperties = new ParagraphProperties();
                                    ContextualSpacing contextualSpacing = new ContextualSpacing();

                                    spaceProperties.Append(contextualSpacing);
                                    p.PrependChild(spaceProperties);
                                }
                                foreach(DocumentFormat.OpenXml.Wordprocessing.TableCell cell in row.Elements<DocumentFormat.OpenXml.Wordprocessing.TableCell>())
                            {
                                    TableCellProperties tableCellProperties = new TableCellProperties();
                                    ContextualSpacing contextualSpacing1 = new ContextualSpacing();
                                    tableCellProperties.Append(contextualSpacing1);
                                    cell.PrependChild(tableCellProperties);

                                    foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph p in cell.Elements<Paragraph>())
                                    {
                                        ParagraphProperties spaceProperties = new ParagraphProperties();
                                        ContextualSpacing contextualSpacing = new ContextualSpacing();

                                        spaceProperties.Append(contextualSpacing);
                                        p.PrependChild(spaceProperties);
                                    }
                            }
                        }
                        }
                        mainPart.Document.Save();
                    }

                    byte[] bytesInStream = generatedDocument.ToArray(); // simpler way of converting to array
                    generatedDocument.Close();

                    Response.Clear();
                    Response.ContentType = contentType;
                    Response.AddHeader("content-disposition", "attachment;filename=" + filename);

                    //this will generate problems
                    Response.BinaryWrite(bytesInStream);
                    try
                    {
                        Response.End();
                    }
                    catch (Exception ex)
                    {
                        //Response.End(); generates an exception. if you don't use it, you get some errors when Word opens the file...
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }

                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Esempio n. 7
1
        static void Main(string[] args)
        {
            CssParser cp = new CssParser();
            cp.AddStyleSheet(@"1_files/quemain.css");
            var html = File.ReadAllText("2.html");
            var htmlText = CssHtmlMerger.MergeHtmlAndCss(cp, html);
            var bodyhtml = htmlText;
            //string body = File.ReadAllText("E:\\N1.txt");
            //mathjax2word.OpenXmlWord word = new mathjax2word.OpenXmlWord("E:\\a4.docx");
            //word.WriteTextToWord(bodyhtml);
            //word.Close();
            //Console.ReadLine();

            #region html 2 openxml
            const string filename = "test.docx";

            if (File.Exists(filename)) File.Delete(filename);

            using (MemoryStream generatedDocument = new MemoryStream())
            {
                // Uncomment and comment the second using() to open an existing template document
                // instead of creating it from scratch.

                byte[] data = Resource1.template;
                generatedDocument.Write(data, 0, data.Length);
                generatedDocument.Position = 0L;
                using (WordprocessingDocument package = WordprocessingDocument.Open(generatedDocument, true))
                //using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                {
                    MainDocumentPart mainPart = package.MainDocumentPart;
                    if (mainPart == null)
                    {
                        mainPart = package.AddMainDocumentPart();
                        new Document(new Body()).Save(mainPart);
                    }

                    HtmlConverter converter = new HtmlConverter(mainPart);
                    //converter.WebProxy.Credentials = new System.Net.NetworkCredential("nizeto", "****", "domain");
                    //converter.WebProxy.Proxy = new System.Net.WebProxy("proxy01:8080");
                    converter.ImageProcessing = ImageProcessing.AutomaticDownload;
                    converter.ProvisionImage += OnProvisionImage;

                    Body body = mainPart.Document.Body;

                    converter.ParseHtml(bodyhtml);
                    mainPart.Document.Save();

                    //AssertThatOpenXmlDocumentIsValid(package);
                }

                File.WriteAllBytes(filename, generatedDocument.ToArray());
            }

            System.Diagnostics.Process.Start(filename);
            #endregion

            #region 1
            // string br = "<w:p><w:r><w:t></w:t></w:r></w:p>";
            // string oxmlText = "<w:p><w:r><w:t>{0}</w:t></w:r></w:p>";

            // var brArray = body.Split(new string[] { "<br>" }, body.Length, StringSplitOptions.None);
            // var strList = new List<string>();
            // for (int k = 0; k < brArray.Length; k++)
            // {
            //     strList.Add(HandleStr(brArray[k]));

            //     strList.Add(br);

            // }

            // var xml = string.Join("", strList);

            // Console.WriteLine(xml);

            // OpenXmlWord word = new OpenXmlWord("E:\\a.docx");

            //// var omml = OpenXmlWord.ConvertMathMl2OMML(xml);
            // word.WriteTextToWord(xml);
            // word.Close();
            // Console.ReadLine();
            #endregion

            #region 2
            //var lmm = new LatexToMathMLConverter(
            //   "E:\\source.txt",
            //  Encoding.UTF8,
            //  "E:\\source.xml");
            ////lmm.ValidateResult = true;
            ////lmm.Convert();
            //var str = lmm.ConvertToText();
            //Console.WriteLine(str);

            //string strText = System.Text.RegularExpressions.Regex.Replace(body, "<[^>]+>", "");
            //strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");
            ////Regex.Match(body,)

            //body.Replace(@"\(", "$");

            //OpenXmlWord word = new OpenXmlWord("E:\\a.docx");
            //var omml = OpenXmlWord.ConvertMathMl2OMML(str);
            //word.WritOfficeMathMLToWord(omml);
            //word.Close();
            //Console.ReadLine();
            #endregion
        }
Esempio n. 8
0
        /// <summary>
        /// Convert html to word
        /// </summary>
        /// <param name="content"></param>
        /// <param name="files"></param>
        /// <returns></returns>
        public byte[] ToDocx(string content, Dictionary <string, byte[]> files)
        {
            using (var generatedDocument = new MemoryStream())
            {
                using (var package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                {
                    var mainPart = package.MainDocumentPart;
                    if (mainPart == null)
                    {
                        mainPart = package.AddMainDocumentPart();
                        new Document(new Body()).Save(mainPart);
                    }

                    var converter = new NotesFor.HtmlToOpenXml.HtmlConverter(mainPart);

                    var imageProvider = new MemoryImageProvider(files);
                    converter.ImageProcessing = ImageProcessing.ManualProvisioning;
                    converter.ProvisionImage += imageProvider.Get;

                    var body = mainPart.Document.Body;

                    var paragraphs = converter.Parse(content);
                    for (int i = 0; i < paragraphs.Count; i++)
                    {
                        body.Append(paragraphs[i]);
                    }

                    mainPart.Document.Save();
                }
                return(generatedDocument.ToArray());
            }
        }
        public ActionResult ExportWord()
        {
            ExportRetailModel model = Session["@ExportWord@"] as ExportRetailModel;
            //render view
            const string viewName = "ViewForWord";
            String       html     = RenderStringView(viewName, model);

            try
            {
                const string filename    = "StreamTest.docx";
                const string contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                using (MemoryStream generatedDocument = new MemoryStream())
                {
                    using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document))
                    {
                        MainDocumentPart mainPart = package.MainDocumentPart;
                        if (mainPart == null)
                        {
                            mainPart = package.AddMainDocumentPart();
                            new HtmlDocument.Document(new HtmlDocument.Body()).Save(mainPart);
                        }
                        if (Request.Url != null)
                        {
                            HtmlXml.HtmlConverter converter = new HtmlXml.HtmlConverter(mainPart)
                            {
                                BaseImageUrl = new Uri(Request.Url.Scheme + "://" + Request.Url.Authority)
                            };
                            HtmlDocument.Body body = mainPart.Document.Body;
                            var paragraphs         = converter.Parse(html);
                            foreach (OpenXmlCompositeElement t in paragraphs)
                            {
                                body.Append(t);
                            }
                        }
                        mainPart.Document.Save();
                    }
                    byte[] bytesInStream = generatedDocument.ToArray(); // simpler way of converting to array
                    generatedDocument.Close();
                    Response.Clear();
                    Response.ContentType = contentType;
                    Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                    //this will generate problems
                    Response.BinaryWrite(bytesInStream);
                    try
                    {
                        Response.End();
                    }
                    catch (Exception ex)
                    {
                        return(new EmptyResult());
                        //Response.End(); generates an exception. if you don't use it, you get some errors when Word opens the file...
                    }
                    Session.Remove("@ExportWord@");
                    return(new EmptyResult());
                }
            }
            catch (Exception ex)
            {
                return(new EmptyResult());
            }
        }