private static byte[] Merge(byte[] dest, byte[] src) { string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString(); var memoryStreamDest = new MemoryStream(); memoryStreamDest.Write(dest, 0, dest.Length); memoryStreamDest.Seek(0, SeekOrigin.Begin); var memoryStreamSrc = new MemoryStream(src); using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStreamDest, true)) { MainDocumentPart mainPart = doc.MainDocumentPart; AlternativeFormatImportPart altPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId); altPart.FeedData(memoryStreamSrc); var altChunk = new AltChunk(); altChunk.Id = altChunkId; OpenXmlElement lastElem = mainPart.Document.Body.Elements<AltChunk>().LastOrDefault(); if(lastElem == null) { lastElem = mainPart.Document.Body.Elements<Paragraph>().Last(); } //Page Brake einfügen Paragraph pageBreakP = new Paragraph(); Run pageBreakR = new Run(); Break pageBreakBr = new Break() { Type = BreakValues.Page }; pageBreakP.Append(pageBreakR); pageBreakR.Append(pageBreakBr); return memoryStreamDest.ToArray(); } }
public void HtmlToWordPartial(string html, string destinationFileName) { using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(destinationFileName, WordprocessingDocumentType.Document)) { string altChunkId = "myId"; MainDocumentPart mainPart = wordDocument.MainDocumentPart; if (mainPart == null) { mainPart = wordDocument.AddMainDocumentPart(); new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()).Save(mainPart); } MemoryStream ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(html)).ToArray()); // Uncomment the following line to create an invalid word document. // MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>")); // Create alternative format import part. AlternativeFormatImportPart formatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId); //ms.Seek(0, SeekOrigin.Begin); // Feed HTML data into format import part (chunk). formatImportPart.FeedData(ms); AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainPart.Document.Body.Append(altChunk); wordDocument.Save(); wordDocument.Close(); } }
public void Update(DocumentFormat.OpenXml.Wordprocessing.Tag tag, string value, MainDocumentPart mainPart) { string mainhtml = "<html><head><style type='text/css'>.catalogGeneralTable{border-collapse: collapse;text-align: left;} .catalogGeneralTable td, th{ padding: 5px; border: 1px solid #999999; } </style></head> <body style='font-family:Trebuchet MS;font-size:.9em;'>" + value + "</body></html>"; int blockLevelCounter = 1; string altChunkId = String.Format("AltChunkId{0}", altChunkIdCounter++); AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId); using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write)) { using (StreamWriter stringWriter = new StreamWriter(chunkStream, Encoding.UTF8)) //Encoding.UTF8 is important to remove special characters { stringWriter.Write(mainhtml); } } AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; SdtBlock sdtBlock = tag.Ancestors <SdtBlock>().Single(); sdtBlock.InsertAt(altChunk, blockLevelCounter++); }
//gavdcodeend 06 //gavdcodebegin 07 public static void WordOpenXmlJoinTwoDocuments() { using (WordprocessingDocument myWordDoc = WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true)) { string altChunkId = "ID" + Guid.NewGuid().ToString(); MainDocumentPart mainPart = myWordDoc.MainDocumentPart; AlternativeFormatImportPart myChunk = mainPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (FileStream fileStream = File.Open(@"C:\Temporary\WordDoc02.docx", FileMode.Open)) myChunk.FeedData(fileStream); AltChunk altChunk = new AltChunk { Id = altChunkId }; mainPart.Document.Body .InsertAfter(altChunk, mainPart.Document.Body.Elements <Paragraph>() .Last()); mainPart.Document.Save(); } }
private static void CombinarDocumentos(List <string> anexos, MainDocumentPart documentoBase) { if (anexos != null) { if (anexos.Count > 0) { foreach (var anexo in anexos) { AlternativeFormatImportPart chunk = documentoBase.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML); using (FileStream fileStream = File.Open(anexo, FileMode.Open)) { chunk.FeedData(fileStream); } AltChunk altChunk = new AltChunk() { Id = documentoBase.GetIdOfPart(chunk) }; Paragraph saltoPagina = new Paragraph(new Run(new Break() { Type = BreakValues.Page })); documentoBase.Document.Body.AppendChild(saltoPagina); documentoBase.Document.Body.AppendChild(altChunk); } //documentoBase.Document.Save(); } } }
/// <summary> /// 將包含 HTML 的內容設定至指定的書籤內 /// (已知問題: 若 HTML 包含圖片,圖片部分會異常無法顯示,待解決) /// </summary> /// <param name="doc">文件</param> /// <param name="BookmarkName">書籤名稱 (有區分大小寫)</param> /// <param name="Html">HTML內容</param> /// <param name="DeleteAFterSetvalue">是否在設定完書籤內容後,將書籤移除 (預設: True)</param> private void SetBookmarkValueWithHtmlValue(WordprocessingDocument doc, string BookmarkName, string Html, bool DeleteAfterSetvalue = true) { StringBuilder xhtmlBuilder = new StringBuilder(); xhtmlBuilder.Append("<HTML>"); xhtmlBuilder.Append("<body>"); xhtmlBuilder.Append(Html); xhtmlBuilder.Append("</body>"); xhtmlBuilder.Append("</HTML >"); string altChunkId = "chunk_" + BookmarkName.ToLower(); AlternativeFormatImportPart chunk = doc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkId); using (MemoryStream xhtmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xhtmlBuilder.ToString()))) { chunk.FeedData(xhtmlStream); AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; var res = from bm in doc.MainDocumentPart.Document.Body.Descendants <BookmarkStart>() where bm.Name == BookmarkName select bm; var bookmark = res.SingleOrDefault(); var parent = bookmark.Parent; parent.InsertAfterSelf(altChunk); if (bookmark != null && DeleteAfterSetvalue) { bookmark.Remove(); } } }
static void DocxMerge(string srcFile1, string srcFile2, string outFile) { File.Delete(outFile); File.Copy(srcFile1, outFile); using (WordprocessingDocument myDoc = WordprocessingDocument.Open(outFile, true)) { string altChunkId = "AltChunkId1"; MainDocumentPart mainPart = myDoc.MainDocumentPart; AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (FileStream fileStream = File.Open(srcFile2, FileMode.Open)) chunk.FeedData(fileStream); AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements <Paragraph>().Last()); mainPart.Document.Save(); } }
private static AltChunk CreateAltChunk( string templateFileName, Dictionary <string, string> contentMap, WordprocessingDocument wordDocument) { // Copy the template file contents to a MemoryStream to be able to // update the content controls without altering the template file. using FileStream fileStream = File.Open(templateFileName, FileMode.Open); using var memoryStream = new MemoryStream(); fileStream.CopyTo(memoryStream); // Open the copy of the template on the MemoryStream, update the // content controls, save the updated template back to the // MemoryStream, and reset the position within the MemoryStream. using (WordprocessingDocument chunkDocument = WordprocessingDocument.Open(memoryStream, true)) { var contentControlWriter = new ContentControlWriter(contentMap); contentControlWriter.WriteContentControls(chunkDocument); } memoryStream.Seek(0, SeekOrigin.Begin); // Create an AlternativeFormatImportPart from the MemoryStream. string altChunkId = "AltChunkId" + Guid.NewGuid(); AlternativeFormatImportPart chunk = wordDocument.MainDocumentPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.WordprocessingML, altChunkId); chunk.FeedData(memoryStream); // Return the w:altChunk element to be added to the w:body element. return(new AltChunk { Id = altChunkId }); }
public WordManipulator AppendOtherWordFile(String wordFilePath, Boolean addPageBreak = true) { MainDocumentPart mainPart = _document.MainDocumentPart; string altChunkId = "AltChunkId" + Guid.NewGuid().ToString(); AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (FileStream fileStream = File.Open(wordFilePath, FileMode.Open)) { chunk.FeedData(fileStream); AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainPart.Document .Body .InsertAfter(altChunk, mainPart.Document.Body .Elements().LastOrDefault()); mainPart.Document.Save(); } if (addPageBreak) { _body.Append( new Paragraph( new Run( new Break() { Type = BreakValues.Page }))); } return(this); }
/// <summary> /// Write docx /// </summary> /// <param name="bookMark"></param> /// <param name="filePath"></param> /// <param name="html"></param> private void WriteDocx(string bookMark, string filePath, string html) { try { string stringToWrite = "<html><head><meta charset=\"UTF-8\"></head><body>" + html + "</body></html>"; MemoryStream memoryStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(stringToWrite)); using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { MainDocumentPart mainPart = doc.MainDocumentPart; IEnumerable <BookmarkStart> rs = from bm in mainPart.Document.Body.Descendants <BookmarkStart>() where bm.Name == bookMark select bm; DocumentFormat.OpenXml.OpenXmlElement bookmark = rs.SingleOrDefault(); if (bookmark != null) { DocumentFormat.OpenXml.OpenXmlElement parent = bookmark.Parent; AltChunk altchunk = new AltChunk(); string chunkId = bookMark + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond; altchunk.Id = chunkId; AlternativeFormatImportPart formatImport = doc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, chunkId); formatImport.FeedData(memoryStream); parent.InsertBeforeSelf(altchunk); } } } catch (Exception ext) { throw ext; } }
/// <summary> /// Append SubDocument at end of current doc /// </summary> /// <param name="content"></param> public void AppendSubDocument(Stream content, bool withPageBreak) { if (wdDoc == null) { throw new InvalidOperationException("Document not loaded"); } AlternativeFormatImportPart formatImportPart = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML); formatImportPart.FeedData(content); AltChunk altChunk = new AltChunk(); altChunk.Id = wdMainDocumentPart.GetIdOfPart(formatImportPart); wdMainDocumentPart.Document.Body.Elements <Paragraph>().Last().InsertAfterSelf(altChunk); if (withPageBreak) { Paragraph p = new Paragraph( new Run( new Break() { Type = BreakValues.Page })); altChunk.InsertAfterSelf(p); } }
/// <summary> /// Merges docxs in a new docx /// </summary> /// <param name="path">A new document destination</param> /// <param name="documents">Documents to be merged</param> private static void GenerateDocument(string path, List <byte[]> documents) { GenerateNewDocx(path); using (WordprocessingDocument mainDoc = WordprocessingDocument.Open(path, true)) { MainDocumentPart mainPart = mainDoc.MainDocumentPart; XDocument mainDocumentXDoc = GetXDocument(mainDoc); foreach (var item in documents) { var currentAltChunkId = findNextIdForAltChunk(mainDocumentXDoc); AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart( "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", currentAltChunkId); chunk.FeedData(GetStream(item)); XElement altChunk = new XElement(w + "altChunk", new XAttribute(r + "id", currentAltChunkId)); mainDocumentXDoc.Root .Element(w + "body") .Elements() .Last() .AddAfterSelf(altChunk); } SaveXDocument(mainDoc, mainDocumentXDoc); } }
//OpenXML Word中写入html private void button9_Click(object sender, EventArgs e) { string docName = @"openxmltest-copy.docx"; File.Copy(@"openxmltest.docx", docName, true); using (WordprocessingDocument doc = WordprocessingDocument.Open(docName, true)) { string altChunkId = "myId"; MainDocumentPart mainDocPart = doc.MainDocumentPart; var run = new DocumentFormat.OpenXml.Wordprocessing.Run(new Text("test")); var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new ParagraphProperties( new Justification() { Val = JustificationValues.Center }), run); //RunProperties runProperties = new RunProperties(); //属性 //RunFonts fonts = new RunFonts() { EastAsia = "DFKai-SB" }; // 设置字体 //FontSize size = new FontSize() { Val = "52" }; // 设置字体大小 //DocumentFormat.OpenXml.Wordprocessing.Color color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "red" }; // 设置字体样式 //// 将样式添加到属性里面 //runProperties.Append(color); //runProperties.Append(size); //runProperties.Append(fonts); //run.Append(runProperties); //paragraph.Append(run); var body = mainDocPart.Document.Body; body.Append(paragraph); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body><h1>HELLO</h1></body></html>")); // Uncomment the following line to create an invalid word document. // MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>")); using (StreamReader reader = new StreamReader("苏州抵押合同模板.html")) //苏州抵押合同模板.html 苏州借款合同模板-3月.html { string content = reader.ReadToEnd(); ms = new MemoryStream(Encoding.UTF8.GetBytes(content)); } // Create alternative format import part. AlternativeFormatImportPart formatImportPart = mainDocPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId); //ms.Seek(0, SeekOrigin.Begin); // Feed HTML data into format import part (chunk). formatImportPart.FeedData(ms); AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; body.Append(altChunk); //mainDocPart.Document.Save(); } }
public void open(string fname) { wordDocument = WordprocessingDocument.Create(fname, WordprocessingDocumentType.Document, true); mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); body = mainPart.Document.AppendChild(new Body()); chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Rtf, altChunkId); }
private string Compose(string[] sourceFiles, string outputFile) { string altChunkIdBase = "acID"; int altChunkCounter = 1; string altChunkId = altChunkIdBase + altChunkCounter.ToString(); // 选择第一个文件为主文件,保留里面的样式 string masterFile = sourceFiles[0]; File.Copy(masterFile, outputFile, true); // 后续文件合并进来 List <string> fileList = sourceFiles.ToList(); fileList.RemoveAt(0); // 打开目标文件进行合并 MainDocumentPart wdDocTargetMainPart = null; Document docTarget = null; AlternativeFormatImportPartType afType; using (WordprocessingDocument wdPkgTarget = WordprocessingDocument.Open(outputFile, true)) { wdDocTargetMainPart = wdPkgTarget.MainDocumentPart; docTarget = wdDocTargetMainPart.Document; Paragraph lastParaTarget = docTarget.Body.Descendants <Paragraph>().Last(); ParagraphProperties paraPropTarget = lastParaTarget.ParagraphProperties; if (paraPropTarget == null) { paraPropTarget = new ParagraphProperties(); } Run paraRun = lastParaTarget.Descendants <Run>().FirstOrDefault(); foreach (string fi in fileList) { afType = AlternativeFormatImportPartType.WordprocessingML; AlternativeFormatImportPart chunk = wdDocTargetMainPart.AddAlternativeFormatImportPart(afType, altChunkId); System.IO.FileStream fsSourceDocument = new FileStream(fi, FileMode.Open); chunk.FeedData(fsSourceDocument); //Create the chunk AltChunk ac = new AltChunk { //Link it to the part Id = altChunkId }; docTarget.Body.Append(ac); docTarget.Save(); altChunkCounter += 1; altChunkId = altChunkIdBase + altChunkCounter.ToString(); chunk = null; ac = null; } } return(outputFile); }
public static int Main(string[] args) { // https://docs.microsoft.com/ja-jp/dotnet/api/documentformat.openxml.wordprocessing.altchunk?view=openxml-2.8.1 var app = new CommandLineApplication(throwOnUnexpectedArg: false); app.Name = nameof(docxmerge); app.Description = "Mearge .docx files. "; app.HelpOption("-h|--help"); app.ExtendedHelpText = @"Merged files should be the end of argument like: docxmerge [options] file1 file2 "; var optionTemplateFile = app.Option( template: "-t|--template", description: "Template filename. merged files will be appended after the contents of template file. ", optionType: CommandOptionType.SingleValue ); var optionOutFile = app.Option( template: "-o|--output", description: "Output filename", optionType: CommandOptionType.SingleValue ); app.OnExecute(() => { var templateFile = optionTemplateFile.Value(); var outFile = optionOutFile.Value(); // Because position of last paragraph is not updated while looping var mergedFiles = app.RemainingArguments; mergedFiles.Reverse(); File.Delete(outFile); File.Copy(templateFile, outFile); using (WordprocessingDocument myDoc = WordprocessingDocument.Open(outFile, true)) { MainDocumentPart mainPart = myDoc.MainDocumentPart; foreach (var f in mergedFiles.Select((Value, Index) => new { Value, Index })) { string altChunkId = $"AltChunkId{f.Index}"; AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.WordprocessingML, altChunkId ); using (FileStream fileStream = File.Open(f.Value, FileMode.Open)) { chunk.FeedData(fileStream); } AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last()); } mainPart.Document.Save(); } }); return app.Execute(args); }
/// <summary> /// Append a list of SubDocuments after the predecessorElement. /// </summary> /// <param name="filesToInsert"></param> /// <param name="insertPageBreaks"></param> /// <param name="predecessorElement"></param> private void AppendStreams(IList <MemoryStream> filesToInsert, bool insertPageBreaks, OpenXmlCompositeElement insertAfterElement) { OpenXmlCompositeElement openXmlCompositeElement = null; foreach (var file in filesToInsert) { using (WordprocessingDocument pkgSourceDoc = WordprocessingDocument.Open(file, true)) { var headers = pkgSourceDoc.MainDocumentPart.Document.Descendants <HeaderReference>().ToList(); foreach (var header in headers) { header.Remove(); } var footers = pkgSourceDoc.MainDocumentPart.Document.Descendants <FooterReference>().ToList(); foreach (var footer in footers) { footer.Remove(); } pkgSourceDoc.MainDocumentPart.Document.Save(); } string altChunkId = "AltChunkId-" + Guid.NewGuid(); AlternativeFormatImportPart chunk = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId); file.Position = 0; chunk.FeedData(file); AltChunk altChunk = new AltChunk() { Id = altChunkId }; if (openXmlCompositeElement == null) { openXmlCompositeElement = insertAfterElement; } if (insertPageBreaks) { var run = new Run(new Break() { Type = BreakValues.Page }); Paragraph paragraph = new Paragraph(run); openXmlCompositeElement.InsertAfterSelf <Paragraph>(paragraph); openXmlCompositeElement = paragraph; } openXmlCompositeElement.InsertAfterSelf <AltChunk>(altChunk); openXmlCompositeElement = altChunk; if (wdDoc == null) { throw new InvalidOperationException("Document not loaded"); } } }
public static void DoConversionViaWord(FileInfo newAltChunkBeforeFi, FileInfo newAltChunkAfterFi, XElement html) { var blankAltChunkFi = new DirectoryInfo(Path.Combine(TestUtil.SourceDir.FullName, "Blank-altchunk.docx")); File.Copy(blankAltChunkFi.FullName, newAltChunkBeforeFi.FullName); using (WordprocessingDocument myDoc = WordprocessingDocument.Open(newAltChunkBeforeFi.FullName, true)) { string altChunkId = "AltChunkId1"; MainDocumentPart mainPart = myDoc.MainDocumentPart; AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart( "application/xhtml+xml", altChunkId); using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write)) using (StreamWriter stringStream = new StreamWriter(chunkStream)) stringStream.Write(html.ToString()); XElement altChunk = new XElement(W.altChunk, new XAttribute(R.id, altChunkId) ); XDocument mainDocumentXDoc = myDoc.MainDocumentPart.GetXDocument(); mainDocumentXDoc.Root .Element(W.body) .AddFirst(altChunk); myDoc.MainDocumentPart.PutXDocument(); } WordAutomationUtilities.OpenAndSaveAs(newAltChunkBeforeFi.FullName, newAltChunkAfterFi.FullName); while (true) { try { using (WordprocessingDocument wDoc = WordprocessingDocument.Open(newAltChunkAfterFi.FullName, true)) { SimplifyMarkupSettings settings2 = new SimplifyMarkupSettings { RemoveMarkupForDocumentComparison = true, }; MarkupSimplifier.SimplifyMarkup(wDoc, settings2); XElement newRoot = (XElement)RemoveDivTransform(wDoc.MainDocumentPart.GetXDocument().Root); wDoc.MainDocumentPart.GetXDocument().Root.ReplaceWith(newRoot); wDoc.MainDocumentPart.PutXDocumentWithFormatting(); } break; } catch (IOException) { System.Threading.Thread.Sleep(50); continue; } } }
private void button2_Click(object sender, EventArgs e) { //AddHeaderFromTo(@"C:\Temp\Teste1.docx", @"C:\Temp\Teste2.docx"); using (WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\Temp\Teste2.docx", true)) { string altChunkId = "AltChunkId5"; MainDocumentPart mainDocPart = doc.MainDocumentPart; AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Rtf, altChunkId); string rtfEncodedString = richTextBox1.Rtf; using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(rtfEncodedString))) { chunk.FeedData(ms); } AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; // Funciona adicionando na sequencia //mainDocPart.Document.Body.InsertAfter(altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last()); //teste para adicionar no cabeçalho //mainDocPart.Document.Body.InsertAfter(altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last()); // itera os elementos do documento //var paragraphs = doc.MainDocumentPart.Document.Body.Elements<Paragraph>(); // Iterate through paragraphs, runs, and text, finding the text we want and replacing it //foreach (Paragraph paragraph in paragraphs) //{ // foreach (Run run in paragraph.Elements<Run>()) // { // foreach (Text text in run.Elements<Text>()) // { // if (text.Text == "CABEÇALHO") // { // text.Text = "CABEÇALHO 2"; // } // } // } //} mainDocPart.Document.Save(); } }
private static AltChunk CreateWordprocessingMLAltChunk(WordprocessingDocument wordDocument) { string altChunkId = "BinaryAltChunkId-" + Guid.NewGuid(); AlternativeFormatImportPart chunk = wordDocument.MainDocumentPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (Stream stream = chunk.GetStream(FileMode.Create)) using (var writer = new BinaryWriter(stream)) { writer.Write(WordprocessingMLBytes); } return(new AltChunk { Id = altChunkId }); }
private void SetHtml(MainDocumentPart mainDocumentPart, string sdtBlockTag, string value, OpenXmlElement elem) { string html = "<html><body><div>" + value + "</div></body></html>"; string altChunkId = sdtBlockTag; MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(html)); AlternativeFormatImportPart formatImportPart = mainDocumentPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.Html, altChunkId); formatImportPart.FeedData(ms); ms.Close(); AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; elem.Append(altChunk); }
private static AltChunk CreateAltChunkFromWordDocument( string sourcePath, WordprocessingDocument destWordDocument) { string altChunkId = "AltChunkId-" + Guid.NewGuid(); AlternativeFormatImportPart chunk = destWordDocument.MainDocumentPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.WordprocessingML, altChunkId); using FileStream fs = File.Open(sourcePath, FileMode.Open); chunk.FeedData(fs); return(new AltChunk { Id = altChunkId }); }
/// <summary> /// Append SubDocument at end of current doc /// </summary> /// <param name="content"></param> /// <param name="withPageBreak">If true insert a page break before.</param> public void AppendSubDocument(Stream content, bool withPageBreak) { if (wdDoc == null) { throw new InvalidOperationException("Document not loaded"); } AlternativeFormatImportPart formatImportPart = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML); formatImportPart.FeedData(content); AltChunk altChunk = new AltChunk(); altChunk.Id = wdMainDocumentPart.GetIdOfPart(formatImportPart); OpenXmlElement lastElement = wdMainDocumentPart.Document.Body.LastChild; if (lastElement is SectionProperties) { lastElement.InsertBeforeSelf(altChunk); if (withPageBreak) { SectionProperties sectionProps = (SectionProperties)lastElement.Clone(); var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); var ppr = new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties(); p.AppendChild(ppr); ppr.AppendChild(sectionProps); altChunk.InsertBeforeSelf(p); } } else { lastElement.InsertAfterSelf(altChunk); if (withPageBreak) { Paragraph p = new Paragraph( new Run( new Break() { Type = BreakValues.Page })); altChunk.InsertBeforeSelf(p); } } }
private static AltChunk CreateAltChunkWithXmlContent( WordprocessingDocument wordDocument, AlternativeFormatImportPartType contentType, string xmlContent) { string altChunkId = "XmlAltChunkId-" + Guid.NewGuid(); AlternativeFormatImportPart chunk = wordDocument.MainDocumentPart.AddAlternativeFormatImportPart( contentType, altChunkId); using (Stream stream = chunk.GetStream(FileMode.Create)) using (var writer = new StreamWriter(stream)) { writer.WriteLine(xmlContent); } return(new AltChunk { Id = altChunkId }); }
private void generatedocxfile(StringBuilder strHTMLContent, string FederationName) { /*t create and init a new docx file and * a WordprocessingDocument object to represent it t*/ string docPath = getPPRPath(); //string docPath=GetSavePath(); DocumentFormat.OpenXml.Packaging.WordprocessingDocument doc = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(docPath + FederationName + ".docx", WordprocessingDocumentType.Document); MainDocumentPart mainDocPart = doc.AddMainDocumentPart(); mainDocPart.Document = new Document(); Body body = new Body(); mainDocPart.Document.Append(body); // Add an aFChunk part to the package string altChunkId = "AltChunkId1"; AlternativeFormatImportPart chunk = mainDocPart .AddAlternativeFormatImportPart( AlternativeFormatImportPartType.Xhtml, altChunkId); string html = strHTMLContent.ToString(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(html))) { chunk.FeedData(ms); } // Add the aFChunk to the document AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainDocPart.Document.Body.Append(altChunk); /*t to save the changes t*/ doc.MainDocumentPart.Document.Save(); doc.Dispose(); }
private AltChunk CreateChunkForHtmlPage(string htmlPage) { var realHtml = $"<html><head></head><body>{htmlPage}</body></html>"; string altChunkId = "myid" + Guid.NewGuid().ToString(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(realHtml))) { // Create alternative format import part. AlternativeFormatImportPart formatImportPart = _document.MainDocumentPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.Html, altChunkId); // Feed HTML data into format import part (chunk). formatImportPart.FeedData(ms); } var altChunk = new AltChunk(); altChunk.Id = altChunkId; return(altChunk); }
public static void AppendOtherWordFile(this Document document, String wordFilePath, Boolean addPageBreak = true) { if (addPageBreak) { document.AddPageBreak(); } MainDocumentPart mainPart = document.MainDocumentPart; string altChunkId = "AltChunkId" + Guid.NewGuid().ToString(); AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (FileStream fileStream = File.Open(wordFilePath, FileMode.Open)) { chunk.FeedData(fileStream); AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainPart.Document .Body .InsertAfter(altChunk, mainPart.Document.Body .Elements().LastOrDefault()); mainPart.Document.Save(); } }
/// <summary> /// Insert a document on bookmark /// </summary> /// <param name="bookmark"></param> /// <param name="content"></param> /// <param name="importType"></param> private void AddAltChunkOnBookmark(string bookmark, Stream content, AlternativeFormatImportPartType importType) { AlternativeFormatImportPart formatImportPart = wdMainDocumentPart.AddAlternativeFormatImportPart(importType); formatImportPart.FeedData(content); AltChunk altChunk = new AltChunk(); altChunk.Id = wdMainDocumentPart.GetIdOfPart(formatImportPart); var bookmarkElement = FindBookmark(bookmark); if (bookmarkElement != null) { var paragraph = bookmarkElement.Ancestors <Paragraph>().LastOrDefault(); // without an empty paragraph after altchunk, the docx might be corrupted if the bookmark is inside a table and the html only contains one paragraph if (paragraph.Ancestors <Table>().Any()) { paragraph.InsertAfterSelf(new Paragraph()); } paragraph.InsertAfterSelf(new AltChunk(altChunk)); } }
public void CreateWordDocument(String file_path, String rtfEncodedString) { using (WordprocessingDocument doc = WordprocessingDocument.Create(file_path, WordprocessingDocumentType.Document)) { // Create main document, add body and paragraph MainDocumentPart mainDocPart = doc.AddMainDocumentPart(); mainDocPart.Document = new Document(); Body body = new Body(); mainDocPart.Document.Append(body); String altChunkId = "Id1"; // Set alternative format RTF to import text AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.Rtf, altChunkId); // Convert rtf to chunk data using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(rtfEncodedString))) { chunk.FeedData(ms); } AltChunk altChunk = new AltChunk(); altChunk.Id = altChunkId; mainDocPart.Document.Body.InsertAt( altChunk, 0); // Save changes to the main document part. mainDocPart.Document.Save(); // Open word compatible aplication ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = file_path; Process.Start(startInfo); } }
private void AddHtmlToDoc(WordprocessingDocument document, string reportHtml) { try { String cid = "chunkid"; Body body = document.MainDocumentPart.Document.Body; ///had to wrap the html inside HTML/BODY tags to export it properly, othwise the file somehow gets corrupted. string htmlFormatted = "<html><body>" + reportHtml + "</body></html>"; MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlFormatted)); AlternativeFormatImportPart formatImportPart = document.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, cid); formatImportPart.FeedData(ms); AltChunk altChunk = new AltChunk(); altChunk.Id = cid; document.MainDocumentPart.Document.Body.Append(altChunk); document.MainDocumentPart.Document.Save(); // here's the magic! //document.Close(); } catch (Exception ex) { throw ex; } }