I am trying to align to center a paragraph but is not having any affection on the paragraph.I am using OpenXml. Below is the code:
//paragraph properties
ParagraphProperties User_heading_pPr = new ParagraphProperties();
//trying to align center a paragraph
Justification justification1 = new Justification() { Val = JustificationValues.Center };
// build paragraph piece by piece
Text text = new Text(DateTime.Now.ToString() + " , ");
Text text1 = new Text(gjenerimi + " , ");
Text text2 = new Text(merreshifren());
var run = new Run();
run.Append(text,text1,text2);
Paragraph newParagraph = new Paragraph(run);
User_heading_pPr.Append(justification1);
newParagraph.Append(User_heading_pPr);
Here is how I am trying to align center the paragraph.
Reverse the order in which you assign text and paragraph properties:
User_heading_pPr.Append(justification1);
Paragraph newParagraph = new Paragraph(User_heading_pPr);
newParagraph.Append(run);
In valid and well-formed Word Open XML the paragraph properties must precede the run. So you have to build the Open XML document the same way.
This is a bit different than object models, the way we're typically used to dealing with them - the order does matter!
Related
I have a method that splits paragraphs into two paragraphs at the same location on the word file.
the logic is working fine but I'm losing the document format and styles.
foreach (Paragraph p in body.Descendants<Paragraph>())
{
//splitting the paragraph
var part2 = p.InnerText.Substring(startIndex);
var part1 = p.InnerText.Substring(0, startIndex);
p.InnerText.Replace(p.InnerText, part1);
p.InnerText.Replace(p.InnerText, part2);
pargs.Add(part1);
pargs.Add(part2);
}
// clean the documetn
body.RemoveAllChildren<Paragraph>();
//re-creat the paragraphs
for (int i = 0; i < pargs.Count; i++)
{
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(pargs[i]));
}
return paras;
above is simplified code
I know that my approach is the cause for this problem since I'm taking the inner text of each paragraph and creating a new paragraph without taking the styles. my question is. is there another approach
If you want to keep the original style, you can just copy run properties and set them in newly created Run.
Something like that (haven't tested though):
var properties = paragraph
.Descendants<Run>()
.First()
.RunProperties
.Clone();
...
var run = newParagraph.AppendChild(new Run()
{
RunProperties = (RunProperties)properties
});
how to add character spacing for range of characters
like i want to give character spacing In word toggling for 2 characters
gg of spacing="Expanded" with By value of 4pt
Open XML has not only SDK, but also a tool for converting any document to C# code.
Best way to find out how to use some word feature is to make 2 short documnets - one with this feature used and the other - without. Then convert both documnets into C# code and compare generated code (you can use WinMerge, for example).
As you wish to apply a style to the middle of a paragraph you will need to have (at least) 3 separate Run elements; the first for the start of the unstyled text, the second for the text that has the spacing and the third for the rest of the unstyled text.
To add the character spacing you need to add a Spacing element to the Run. The Spacing element has a Value property that sets the spacing you want in twentieths of a point (so to get 4pt you need to set the Value to 80).
The following code will create a document with spacing on the gg in the word toggling
public static void CreateDoc(string fileName)
{
// Create a Wordprocessing document.
using (WordprocessingDocument package =
WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
// Add a new main document part.
package.AddMainDocumentPart();
//create a body and a paragraph
Body body = new Body();
Paragraph paragraph = new Paragraph();
//add the first part of the text to the paragraph in a Run
paragraph.AppendChild(new Run(new Text("This sentence has spacing between the gg in to")));
//create another run to hold the text with spacing
Run secondRun = new Run();
//create a RunProperties with a Spacing child.
RunProperties runProps = new RunProperties();
runProps.AppendChild(new Spacing() { Val = 80 });
//append the run properties to the Run we wish to assign spacing to
secondRun.AppendChild(runProps);
//add the text to the Run
secondRun.AppendChild(new Text("gg"));
//add the spaced Run to the paragraph
paragraph.AppendChild(secondRun);
//add the final text as a third Run
paragraph.AppendChild(new Run(new Text("ling")));
//add the paragraph to the body
body.AppendChild(paragraph);
package.MainDocumentPart.Document = new Document(body);
// Save changes to the main document part.
package.MainDocumentPart.Document.Save();
}
}
The above produces the following:
Note that you can set the Value of the Spacing to a negative number and the text will be condensed rather than expanded.
I'm trying to add a TextField (acrofield) in the middle of a Paragraph sentence using iTextSharp. An example would be "The Effective Date is [Day] day of [Month], [Year] that this will begin."
Things I have tried:
Paragraph para1 = new Paragraph();
para1.Add(New Phrase("The Effective Date is",fontBold));
//The next line is where it breaks, "Insertion of illegal Element: 30"
para1.Add(CreateTextField("Day",1,0)); //this function returns a PdfPCell.
PdfPCell tempCell = new PdfPCell();
tempCell.AddElement(new Phrase("The Effective Date is",fontBold));
//the next line breaks as well, "Element not allowed."
tempCell.AddElement(CreateTextField("Day",1,0));
Paragraph para1 = new Paragraph();
para1.Add(New Phrase("The Effective Date is",fontBold));
para1.AddSpecial(CreateTextField("Day",1,0));
//This doesn't generate an error, but the TextField is not displayed on PDF
Paragraph para1 = new Paragraph();
PdfPTable tempTable = new PdfPTable(1);
para1.Add(New Phrase("Hello",fontBold));
tempTable.AddCell(CreateTextField("Day",1,0));
para1.Add(tempTable);
para1.Add(New Phrase("World",fontBold));
//This doesn't generate an error, but the TextField is not displayed on PDF
I know the CreateTextField(...) works because I am using it in several other places on the page.
How can I add a TextField inline with other text without using tables and tediously trying to manipulate cell size to accommodate what I need?
Thanks for the help!
Your question is wrong. You don't want to add a PdfPCell to a Paragraph. You want to create inline form fields. That's a totally different question.
Take a look at the GenericFields example. In this example, we create the Paragraph you need like this:
Paragraph p = new Paragraph();
p.add("The Effective Date is ");
Chunk day = new Chunk(" ");
day.setGenericTag("day");
p.add(day);
p.add(" day of ");
Chunk month = new Chunk(" ");
month.setGenericTag("month");
p.add(month);
p.add(", ");
Chunk year = new Chunk(" ");
year.setGenericTag("year");
p.add(year);
p.add(" that this will begin.");
Do you see how we add empty Chunks where you want to add a PdfPCell? We use the setGenericTag() method on these Chunk object to add a form field where ever the Chunks are rendered.
For this to work, we need to declare a page event:
writer.setPageEvent(new FieldChunk());
The FieldChunk class looks like this:
public class FieldChunk extends PdfPageEventHelper {
#Override
public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
TextField field = new TextField(writer, rect, text);
try {
writer.addAnnotation(field.getTextField());
} catch (IOException ex) {
throw new ExceptionConverter(ex);
} catch (DocumentException ex) {
throw new ExceptionConverter(ex);
}
}
}
Every time a "generic chunk" is rendered, the onGenericTag() method will be called passing the parameter we used in the setGenericTag() method as the text parameter. We use the writer, rect and text parameters to create and add a TextField. The result looks like this:
Feel free to adapt rect if you want to create a bigger text field.
Important: my example is written in Java. If you want to port the example to C#, just change the first letter of each method to upper case (e.g. change add() into Add()). If that doesn't work, try setting the parameter as a member variable (e.g. change writer.setPageEvent(event) into writer.PageEvent = event).
Update: If you want to make the field bigger, you should create a new Rectangle. For instance:
Rectangle rect2 = new Rectangle(rect.Left, rect.Bottom - 5, rect.Right, rect.Top + 2);
TextField field = new TextField(writer, rect2, text);
I want to colourise my amino acids 1 letter codes automatically from the c# from which they are currently output.
The spreadsheet is output correctly and I have a column such as this example:
A B
1 KJAGLKJGKASLJG
2 FLFSFHDSHDSHHF
3 KJSDALKDJKLFJK
4 KLFDJSHASDFFSD
Every distinct character will be assigned its own colour. For example, K would be Red, L would be Yellow, and D would be Orange. This must be done with the Open XML SDK and not Excel COM programming or a VBA script.
At the moment, this is how the cells are output, but they use the default style sheet.
string columnName = AlphabetLetterRollOver((int) columnIndex);
string cellRef = columnName + (rowIndex + 1);
Cell cell1 = new Cell {CellReference = cellRef, StyleIndex = 1U};
cell1.DataType = CellValues.String;
CellValue cellValue1 = new CellValue();
cellValue1.Text = columnValue;
cell1.Append(cellValue1);
row1.Append(cell1);
I tried the following code as a test case to achieve what I want, but it did not work; it throws an exception:
RunProperties runProperties = new RunProperties();
FontSize fontSize = new FontSize() {Val = 10D};
Color color = new Color() {Rgb = "FF000000"};
RunFont runFont = new RunFont() {Val = "Consolas"};
FontFamily fontFamily = new FontFamily() {Val = 3};
runProperties.Append(fontSize);
runProperties.Append(color);
runProperties.Append(runFont);
runProperties.Append(fontFamily);
Run run = new Run();
Text text = new Text();
text.Text = "A";
run.Append(runProperties);
run.Append(text);
cell1.Append(run);
row1.Append(cell1);
This exception thrown is as follows:
Exception: System.InvalidOperatioonException
Message: Cannot insert the OpenXmlElement "newChild" because it is part of a tree.
Source: DocumentFormat.OpenXml
StrackTrace: at DocumentFormat.OpenXml.OpenXmlCompositeElement.AppendChild[T](T newChild)
at DocumentFormat.OpenXml.OpenXmlElement.Append(OpenXmlElement[] newChildren)
Any ideas will be appreciated, thanks!
What you need to do is create shared strings with each letter set to color you need. Then append as many of them to cells you want.
EDIT -
Download OpenXMLSDKToolV25.msi
Now here is the trick, OpenXML productivity tool is the one you need here. It allows you to brows an existing Excel file and break it down to CODES : watch
Now what you need to do is create an Excel sheet manually with what you want [In your case having multi colur text] Then open this Excel file with productivity tool and understand the CODE . Note that you will need to understand Spreadsheet file structure to understand this CODE [ Refer this] .. Now write your codes to meet your requirement using codes of Productivity tool
NOTE - Once you analyse the dummy Spreadsheet with Productivity tool you will understand why giving or guiding with CODE examples as an answer is not practical. Just try with A cell with multicolor texts
So, I want to export my data from database to Ms Word using openXML. I formatting my paragraph as below
para = new Paragraph();
run = new Run(new Text(row["name"].ToString()));
paraProp = new ParagraphProperties();
spacing = new SpacingBetweenLines() { Before = "60", After = "60" };
paraProp.Append(spacing);
para.Append(paraProp);
para.Append(run);
The problem is some data is empty, and this make my paragraph formatting not working.
I try to add empty space like this
run = new Run(new Text(row["name"].ToString() + " "));
But it also not working.
So how to apply paragraph formatting even the data is empty?
I am guessing the empty paragraphs are not spacing properly and causing your formatting issues.
Try changing your spacingbetweenlines properties to:
{ After = "60", Before = "60" Line = "240", LineRule = LineSpacingRuleValues.Exact};
The Line value is the height of the line and the and the LineRule sets how the before and after are applied to the paragraph.