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; }
// 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; }
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); } }
/// <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()); } }