How to create a textbox in word openxml using c# - c#

I am trying to create a textbox using the openxml nuget for a word document. I can't seem to any resources regarding how to add a textbox to my page
Here is what I have tried
using (MemoryStream memory = new MemoryStream())
{
// Create Document
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(memory, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body docBody = new Body();
TextBox testBox = new TextBox();
TextBoxContent textBoxContent = new TextBoxContent();
Paragraph paragraph = new Paragraph();
Run run = new Run();
Text text = new Text("test");
run.Append(text);
paragraph.Append(run);
textBoxContent.Append(paragraph);
testBox.Append(textBoxContent);
docBody.Append(testBox);
mainPart.Document.Append(docBody);
wordDocument.Save();
}
//Download File
return new MemoryStream(memory.ToArray());
}
The shown code gives me corrupted word error. How am i supposed to append the elements for it to work ?

Related

Why is my document.Add(paragraph) not working (wpf, iText)?

I am trying to create a pdf using iText in WPF. But I am not able to add any paragraphs to my document.
Here's my code:
string destination = "po.pdf";
var fos = File.Create(destination);
PdfWriter writer = new PdfWriter(fos);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf, PageSize.A4.Rotate());
Paragraph p1 = new Paragraph();
p1.Inlines.Add(new TextBlock()
{
Text = "hello"
});
document.Add(p1);
document.Close();
}
Here, in the second last line (document.Add(p1)), I get a red underline under 'p1'.
The error says --- Cannot convert from 'System.Windows.Documents.Paragraph' to 'iText.Layout.Element.AreaBreak'.
Thank you in advance.

Generate Docx files using html and css with DocumentFormat.OpenXml in ASP.Net Core 2.2

Is it possible to generate Docx files from HTML and CSS using DocumentFormat.OpenXml ?
I want to create an Web API application using ASP.Net Core 2.2 that generates Docx files, and another applications that need to generate Docx, call my Docx generator application.
In other word I want to create an Docx generator that another applications can get help from that(other applications that wants to get help from my Docx generator, can be implemented by any programming language like JavaScript).
Only way that I find to communicate between my applications, is use HTML and CSS strings to generate Docx files from their.
off course, if is possible another better way to do this job, please explains that for me.
currently I'm using DocumentFormat.OpenXml to generate Docx files.
using (MemoryStream mem = new MemoryStream())
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
{
wordDoc.AddMainDocumentPart();
// siga a ordem
Document doc = new Document();
Body body = new Body();
// 1 paragrafo
Paragraph para = new Paragraph();
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Normal" };
Justification justification1 = new Justification() { Val = JustificationValues.Center };
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
paragraphProperties1.Append(paragraphStyleId1);
paragraphProperties1.Append(justification1);
paragraphProperties1.Append(paragraphMarkRunProperties1);
Run run = new Run();
RunProperties runProperties1 = new RunProperties();
Text text = new Text() { Text = "The OpenXML SDK rocks!" };
// siga a ordem
run.Append(runProperties1);
run.Append(text);
para.Append(paragraphProperties1);
para.Append(run);
// 2 paragrafo
Paragraph para2 = new Paragraph();
ParagraphProperties paragraphProperties2 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId2 = new ParagraphStyleId() { Val = "Normal" };
Justification justification2 = new Justification() { Val = JustificationValues.Start };
ParagraphMarkRunProperties paragraphMarkRunProperties2 = new ParagraphMarkRunProperties();
paragraphProperties2.Append(paragraphStyleId2);
paragraphProperties2.Append(justification2);
paragraphProperties2.Append(paragraphMarkRunProperties2);
Run run2 = new Run();
RunProperties runProperties3 = new RunProperties();
Text text2 = new Text();
text2.Text = "Teste aqui";
run2.AppendChild(new Break());
run2.AppendChild(new Text("Hello"));
run2.AppendChild(new Break());
run2.AppendChild(new Text("world"));
para2.Append(paragraphProperties2);
para2.Append(run2);
// todos os 2 paragrafos no main body
body.Append(para);
body.Append(para2);
doc.Append(body);
wordDoc.MainDocumentPart.Document = doc;
wordDoc.Close();
}
return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");
}

Html Text Content to Word using OpenXml

I have a rich text box which contains html formatted text as well as we can insert a copied images. I tried with AlternativeFormatImportPart and AltChunk method. It's generating the document but getting the below error. Please let me know what am I missing here.
MemoryStream ms;// = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(h)).ToArray());
ms = new MemoryStream(HtmlToWord(fileContent));
//MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(h));
// Create alternative format import part.
AlternativeFormatImportPart chunk =
mainDocPart.AddAlternativeFormatImportPart(
"application/xhtml+xml", altChunkId);
chunk.FeedData(ms);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
public static byte[] HtmlToWord(String html)
{
const string filename = "test.docx";
if (File.Exists(filename)) File.Delete(filename);
var doc = new 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);
converter.ExcludeLinkAnchor = true;
converter.RefreshStyles();
converter.ImageProcessing = ImageProcessing.AutomaticDownload;
//converter.BaseImageUrl = new Uri(domainNameURL + "Images/");
converter.ConsiderDivAsParagraph = false;
Body body = mainPart.Document.Body;
var paragraphs = converter.Parse(html);
for (int i = 0; i < paragraphs.Count; i++)
{
body.Append(paragraphs[i]);
}
mainPart.Document.Save();
}
return generatedDocument.ToArray();
}
}
There are some issues in AlternativeFormatImportPart with MemoryStream, document is not getting formatted well. So followed an alternate approach, using HtmlToWord method saved the html content into word and read the file content using FileStream and feed the AlternativeFormatImportPart.
string docFileName;
HtmlToWord(fileContent, out docFileName);
FileStream fileStream = File.Open(docFileName, FileMode.Open);
// Create alternative format import part.
AlternativeFormatImportPart chunk =mainDocPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
chunk.FeedData(fileStream);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;

Search And Replace Text in OPENXML (Added file)

I know there is alot of posts on it, BUT nothing worked for my problem:
Im using OPENxml to create word document, and I am adding some ready files to the document during the creation. I want to change some text in the file that I am adding after the document is ready. So thats what I tried:
First creating the document:
fileName = HttpContext.Current.Server.MapPath("~/reports/"+fileName+".docx");
using (var doc = WordprocessingDocument.Create(
fileName, WordprocessingDocumentType.Document))
{
///add files and content inside the document
addContentFile("template1part1", HttpContext.Current.Server.MapPath("~/templates/template1part1.docx"), mainPart);
}
this is how I am adding the files:
private static void addContentFile(string id,string path, MainDocumentPart mainPart){
string altChunkId = id;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (FileStream fileStream = File.Open(path, FileMode.Open))
{
chunk.FeedData(fileStream);
fileStream.Close();
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainPart.Document.Body.Append(altChunk);
mainPart.Document.Save();
}
And this is how I am trying to replace text AFTER I created the file (after i finished to use WordprocessingDocument)
First try:
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
docText = sr.ReadToEnd();
docText = new Regex(findText, RegexOptions.IgnoreCase).Replace(docText, replaceText);
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
sw.Write(docText);
}
Second try:
using ( WordprocessingDocument doc =
WordprocessingDocument.Open(#"yourpath\testdocument.docx", true))
{
var body = doc.MainDocumentPart.Document.Body;
var paras = body.Elements<Paragraph>();
foreach (var para in paras)
{
foreach (var run in para.Elements<Run>())
{
foreach (var text in run.Elements<Text>())
{
if (text.Text.Contains("text-to-replace"))
{
text.Text = text.Text.Replace("text-to-replace", "replaced-text");
}
}
}
}
}
}
None of them worked, and I tried much more.
Its worked for text that I am manually add to the document, but its now working for text that I am adding from the ready files.
there is a way to do it?
The way you are adding the files are using altchuncks. But you are trying to replace things as if you are modifying the resulting document's openxml.
When you merge documents as altchuncks you are basically adding them as embedded external files to the original document but not as openxml markup. Which means you cannot treat the additional attached documents as openxml documents.
If you want to achieve what you are trying, you have to merge the documents as explained in my answer here - https://stackoverflow.com/a/18352219/860243 which makes the resulting document a proper openxml document. Which allows you to modify it later as you wish.

create word document with Open XML

I am creating a sample handler to generate simple Word document.
This document will contains the text Hello world
This is the code I use (C# .NET 3.5),
I got the Word document created but there is no text in it, the size is 0.
How can I fix it?
(I use CopyStream method because CopyTo is available in .NET 4.0 and above only.)
public class HandlerCreateDocx : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
using (MemoryStream mem = new MemoryStream())
{
// Create Document
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("Hello world!"));
mainPart.Document.Save();
// Stream it down to the browser
context.Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
context.Response.ContentType = "application/vnd.ms-word.document";
CopyStream(mem, context.Response.OutputStream);
context.Response.End();
}
}
}
// Only useful before .NET 4
public void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
This works for me, by putting the streaming code in the outer USING block.
This causes a call to WordprocessingDocument.Close (via the Dispose method).
public void ProcessRequest(HttpContext context)
{
using (MemoryStream mem = new MemoryStream())
{
// Create Document
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("Hello world!"));
mainPart.Document.Save();
}
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
context.Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
mem.Seek(0, SeekOrigin.Begin);
mem.CopyTo(context.Response.OutputStream);
context.Response.Flush();
context.Response.End();
}
}
I have modifed your code to make it work. I can open it correctly after save download it.
Please see my modified below. Hope this help.
using (MemoryStream documentStream = new MemoryStream())
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true))
{
// Add a new main document part.
MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
//Create Document tree for simple document.
mainPart.Document = new Document();
//Create Body (this element contains
//other elements that we want to include
Body body = new Body();
//Create paragraph
Paragraph paragraph = new Paragraph();
Run run_paragraph = new Run();
// we want to put that text into the output document
Text text_paragraph = new Text("Hello World!");
//Append elements appropriately.
run_paragraph.Append(text_paragraph);
paragraph.Append(run_paragraph);
body.Append(paragraph);
mainPart.Document.Append(body);
// Save changes to the main document part.
mainPart.Document.Save();
myDoc.Close();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
SetContentType(context.Request, context.Response, "Simple.docx");
documentStream.Seek(0, SeekOrigin.Begin);
documentStream.CopyTo(context.Response.OutputStream);
context.Response.Flush();
context.Response.End();
}
}
string Filepath = #"C:\Users\infinity\Desktop\zoyeb.docx";
using (var wordprocessingDocument = WordprocessingDocument.Create(Filepath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordprocessingDocument.AddMainDocumentPart();
mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
Body body = mainPart.Document.AppendChild(new Body());
DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("siddiq"));
wordprocessingDocument.MainDocumentPart.Document.Save();
}
go to nuget package manager and install this first into your project
Install-Package DocumentFormat.OpenXml -Version 2.8.1

Categories

Resources