Styling Run/Paragraph to support both RTL and LTR words - c#

How can I style a Run and/or Paragraph to support both RTL and LTR words?
The problem is: I have a complex text which contains both Persian and English words, and I'm trying to create a .docx document using OpenXML SDK. But, the English words, get RTL too. Assume I have this text:
این متن Javad Amiry انگلیسی ست و باید چپ به راست شود.
I'm expecting to place the text in document like this:
But I'm getting this one:
As you can see, English words are vise-versa! Means, while I'm expecting Javad Amiry, I'm getting davaJ yrimA! Do you have any idea to fix that?
The style I'm using is shown below:
var text = "این متن Javad Amiry انگلیسی ست و باید چپ به راست شود.";
var par = new Paragraph();
var pPr = new ParagraphProperties(
new BiDi(),
new Justification { Val = JustificationValues.Both },
new RunFonts {
Ascii = "Arial",
HighAnsi = "Arial",
EastAsia = "Arial",
ComplexScript = "B Mitra",
Hint = FontTypeHintValues.ComplexScript,
},
new FontSize { Val = "24" },
new FontSizeComplexScript { Val = "24" },
new Languages { Bidi = "fa-IR", Val = "en-US", EastAsia = "en-US" }
);
var rPr = new RunProperties(
new RightToLeftText(),
new RunFonts {
Ascii = "Arial",
HighAnsi = "Arial",
EastAsia = "Arial",
ComplexScript = "B Mitra",
Hint = FontTypeHintValues.ComplexScript
},
new FontSize { Val = "24" },
new FontSizeComplexScript { Val = "24" },
new Languages { Bidi = "fa-IR", Val = "en-US", EastAsia = "en-US" },
new BiDi { Val = true }
);
var run = new Run();
run.AppendChild(rPr);
run.AppendChild(new Text(text));
par.AppendChild(pPr);
par.AppendChild(run);
// finally append to the body
body.Append(par);
Thanks in advance.

Well I finally figured-out the problem. The problem was RightToLeftText which I have added to Run. I replaced it with a BiDi and problem solved. Cheers.

Related

c# DinkToPdf - wkhtmltopdf generate incorrect layout from html

I try convert html to PDF by following code but output PDF is not correct layout as HTML page:
var pdf = new HtmlToPdfDocument()
{
GlobalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4,
Margins = new MarginSettings { Top = 12, Left = 12, Right = 12, Bottom = 12 },
DocumentTitle = "",
Out = filenames
},
Objects = { new ObjectSettings
{
PagesCount = true,
HtmlContent = html,
WebSettings = { DefaultEncoding = "utf-8" },
HeaderSettings = { FontName = "Arial", FontSize = 8, Left = $"PTT Group Ship Vetting - {id}", Right = "Page [page] of [toPage]", Line = false },
} }
};
var converter = new SynchronizedConverter(new PdfTools());
byte[] pdfByte = converter.Convert(pdf);
this is HTML input
This is PDF output

NoTextEdit ShapeLock is not working - OpenXML SDK

I am trying to make a TextBox locked by using OpenXML SDK. I've tried this method but the TextBox NoTextEdit is not working.
public DocumentFormat.OpenXml.Presentation.Shape GenerateShape(string StrText)
{
DocumentFormat.OpenXml.Presentation.Shape shape1 = new DocumentFormat.OpenXml.Presentation.Shape();
DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties nonVisualShapeProperties1 = new DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties();
DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties nonVisualDrawingProperties1 = new DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties() { Id = (UInt32Value)3U, Name = "ID",Hidden=true ,Description="Do not Remove" ,MCAttributes=null };
DocumentFormat.OpenXml.Presentation.NonVisualShapeDrawingProperties nonVisualShapeDrawingProperties1 = new DocumentFormat.OpenXml.Presentation.NonVisualShapeDrawingProperties();
Drawing.ShapeLocks shapeLocks1 = new Drawing.ShapeLocks() { NoTextEdit = true, NoGrouping = true,NoMove=true,NoSelection=true,NoEditPoints=true ,NoAdjustHandles=true ,NoRotation=true,NoChangeArrowheads=true,NoChangeAspect=true,NoChangeShapeType=true,NoResize=true};
nonVisualShapeDrawingProperties1.Append(shapeLocks1);
ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties1 = new ApplicationNonVisualDrawingProperties();
PlaceholderShape placeholderShape1 = new PlaceholderShape() { Type = PlaceholderValues.SubTitle, Index = (UInt32Value)1U };
applicationNonVisualDrawingProperties1.Append(placeholderShape1);
nonVisualShapeProperties1.Append(nonVisualDrawingProperties1);
nonVisualShapeProperties1.Append(nonVisualShapeDrawingProperties1);
nonVisualShapeProperties1.Append(applicationNonVisualDrawingProperties1);
DocumentFormat.OpenXml.Presentation.ShapeProperties shapeProperties1 = new DocumentFormat.OpenXml.Presentation.ShapeProperties();
DocumentFormat.OpenXml.Presentation.TextBody textBody1 = new DocumentFormat.OpenXml.Presentation.TextBody();
Drawing.BodyProperties bodyProperties1 = new Drawing.BodyProperties();
Drawing.ListStyle listStyle1 = new Drawing.ListStyle();
Drawing.TextShape shp = new Drawing.TextShape();
Drawing.Paragraph paragraph1 = new Drawing.Paragraph();
Drawing.EndParagraphRunProperties endParagraphRunProperties1 = new Drawing.EndParagraphRunProperties() { Language = "en-US" ,Dirty=false };
paragraph1.Append(GenerateRun(StrText));
paragraph1.Append(endParagraphRunProperties1);
textBody1.Append(bodyProperties1);
textBody1.Append(listStyle1);
textBody1.Append(paragraph1);
shape1.Append(nonVisualShapeProperties1);
shape1.Append(shapeProperties1);
shape1.Append(textBody1);
return shape1;
}
public Drawing.Run GenerateRun(string StrText)
{
Drawing.Run run1 = new Drawing.Run();
Drawing.RunProperties runProperties1 = new Drawing.RunProperties() { Language = "en-US", Dirty = false };
runProperties1.SetAttribute(new OpenXmlAttribute("", "smtClean", "", "0"));
Drawing.Text text1 = new Drawing.Text();
text1.Text = StrText;
Drawing.SolidFill solidFill2 = new Drawing.SolidFill();
Drawing.SchemeColor schemeColor = new Drawing.SchemeColor();
string y = System.Drawing.Color.Transparent.ToArgb().ToString("X");
Drawing.RgbColorModelHex rgbColorModelHex2 = new Drawing.RgbColorModelHex() { Val = "FFFFFF" };//Set Font-Color to Blue (Hex "0070C0").
solidFill2.Append(rgbColorModelHex2);
runProperties1.Append(solidFill2);
Color color = new Color() { Val = "365F91", ThemeColor = ThemeColorValues.Accent1, ThemeShade = "BF" };
run1.Append(runProperties1);
run1.Append(text1);
return run1;
}
Everything works fine except editing. Still the user can edit the TextBox values by double clicking it. How can I avoid this ?
Is there any permanent solution to prevent editing ? Please help me to find a better solution.
Thanks in advance
By researching and communications with the MVP team I've pointed out that there is no way to Protect the TextBox from editing.
As Cindy Meister mentioned in the comments,
Are you able to do it in the PowerPoint application user interface? If not, then Open XML cannot do it... If yes, you can.
If you do not want to text to be changed , Just change it as image then lock that by using NoSelection=true/1 and NoMove=true/1 properties. If you enable these properties the user can't either delete nor change it's position.
For your ref: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_powerpoint-mso_windows8-mso_2016/shape-lock-is-not-working/c1705b55-d2aa-4adb-b538-574ed2fc8eca?tm=1579265435636&page=1&rtAction=1579495439869

OpenXml (.net): SimpleField is not formated

I tried to create a word document with page number in Header. I used SimpleField to insert Page number and page count.
But, these fields are not impacted by Color and font size defined in the RunProperties, unlike the text (as it's showed in the picture below).
How to format SimpleField??
Thanks
private static void CreateReport(string filename)
{
using (var mem = new MemoryStream())
{
using (var wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure
mainPart.Document = new Document();
mainPart.Document.Body = new Body();
//Create paragraph for header
var paragraph = new Paragraph();
var run = paragraph.AppendChild(new Run());
run.Append(new RunProperties()
{
Bold = new Bold(),
FontSize = new FontSize() { Val = "48" },
Color = new Color() { Val = "FF0000" /*red*/ }
}
);
run.Append(new Text() { Text = "Page:" });
run.Append(new SimpleField() { Instruction = #"PAGE" });
run.Append(new Text() { Text = "/" });
run.Append(new SimpleField() { Instruction = #"SECTIONPAGES" });
//Add paragraph to header
AddParagraphToHeader(mainPart, paragraph);
//Save document
wordDocument.SaveAs(filename);
}
}
}
private static void AddParagraphToHeader(MainDocumentPart mainPart, Paragraph paragraph)
{
var part = mainPart.AddNewPart<HeaderPart>();
var header = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
header.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
header.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
header.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
header.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
header.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
header.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
header.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
header.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
header.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
header.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
header.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
header.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
header.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
header.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
header.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
paragraph.RsidParagraphAddition = "00164C17";
paragraph.RsidRunAdditionDefault = "00164C17";
header.Append(paragraph);
part.Header = header;
var headerPartId = mainPart.GetIdOfPart(part);
mainPart.Document.PrependChild<HeaderReference>((new HeaderReference() { Id = headerPartId }));
}
After fighting with this, I found a solution that works for me -- SimpleField is the wrong thing to use for this scenario, you need to end up with a w:instrText by generating FieldChar and FieldCode objects, which means your code needs to be something like this:
Run PageNumRun = new Run(
new Text() { Text = "PAGE ", Space = SpaceProcessingModeValues.Preserve },
new FieldChar { FieldCharType = FieldCharValues.Begin },
new FieldCode("PAGE"), // This is the "Instruction" from the SimpleField
new FieldChar { FieldCharType = FieldCharValues.End },
new Text() { Text = " OF ", Space = SpaceProcessingModeValues.Preserve },
new FieldChar { FieldCharType = FieldCharValues.Begin },
new FieldCode("NUMPAGES"), // This is the "Instruction" from the SimpleField
new FieldChar { FieldCharType = FieldCharValues.End }
);
This will honor your Run font characteristics for the automatically generated values.

Exporting OxyPlot chart to png in asp.net phoject

I'm using asp.net for generating pdf file. In pdf i must show plot. I decided using oxyplot with exporting it in png and inserting in pdf. The documentation says using PlotModel, filling it with series and axes and simply export by using PngExporting object. But when I'm trying generate it, nothing is presented except the axes.
The code I'm using:
var _plotModel = new OxyPlot.PlotModel()
{
PlotAreaBorderColor = OxyPlot.OxyColors.Transparent,
LegendBorder = OxyPlot.OxyColors.Transparent,
TitleToolTip = "Temperature",
Culture = new System.Globalization.CultureInfo("ru-Ru"),
Series =
{
new OxyPlot.Series.LineSeries()
{
ItemsSource = new List<SimplePointModel>
{
new SimplePointModel { Date = DateTime.Now, Temperature = 36.6f },
new SimplePointModel { Date = DateTime.Now.AddDays(1), Temperature = 42.6f },
new SimplePointModel { Date = DateTime.Now.AddDays(2), Temperature = 48.6f },
},
MarkerFill = OxyPlot.OxyColor.Parse("#A9CF9C"),
MarkerType = OxyPlot.MarkerType.Circle,
MarkerSize = item.ListSegments[0].Count() == 1 ? 2 : 1,
DataFieldX = "Date",
DataFieldY = "Temperature",
XAxisKey = "Date",
YAxisKey = "Temperature",
Color = OxyPlot.OxyColor.Parse("#A9CF9C"),
}
},
Axes =
{
new OxyPlot.Axes.DateTimeAxis()
{
Position = OxyPlot.Axes.AxisPosition.Bottom,
Key = "Date",
ToolTip = "Temperature",
AbsoluteMinimum = OxyPlot.Axes.Axis.ToDouble(DateTime.Now.Date),
AbsoluteMaximum = OxyPlot.Axes.Axis.ToDouble(DateTime.Now.AddDays(10000))
},
new OxyPlot.Axes.LinearAxis()
{
Position = OxyPlot.Axes.AxisPosition.Left,
Key = "Temperature",
ToolTip = "Temperature",
IsZoomEnabled = false,
IsPanEnabled = false,
}
}
};
using (var stream = System.IO.File.Create(Path.Combine(folder, "temp.png")))
{
PngExporter.Export(_plotModel, stream, 800, 400, OxyPlot.OxyColors.Transparent);
}
What can I do?
I found solution: we must load data to Points list parameter in Series object instead of ItemSource parameter. ItemSource parameter used in mobile version of library.

How to paginate a Word document from c# with Open XML

How to paginate a word document for example
if there are 10 pages:
page 1 of 10
Page 2 of 10 ...
if there are 15 pages
1 of 15 Page
2 of 15 ...
and so on to generate a dynamic number of pages
It has been three years since you asked your question but maybe I can help other people that are facing this problem.
Here is the code that can paginate a word document.
string documentPath = #"C:\Temp\FooterPOC.docx";
using (WordprocessingDocument package =
WordprocessingDocument.Create(
documentPath, WordprocessingDocumentType.Document))
{
{
MainDocumentPart objMainDocumentPart = package.AddMainDocumentPart();
Document objDocument = new Document();
objMainDocumentPart.Document = objDocument;
Body objBody = new Body();
SectionProperties objSectionProperties = new SectionProperties();
FooterPart objFootPart = objMainDocumentPart.AddNewPart<FooterPart>();
Footer objFooter = new Footer();
objFootPart.Footer = objFooter;
Paragraph objParagraph_1 = new Paragraph();
ParagraphProperties objParagraphProperties = new ParagraphProperties();
ParagraphStyleId objParagraphStyleId = new ParagraphStyleId() { Val = "Footer" };
objParagraphProperties.Append(objParagraphStyleId);
Justification objJustification = new Justification() { Val = JustificationValues.Right };
objParagraphProperties.Append(objJustification);
objParagraph_1.Append(objParagraphProperties);
Run objRun_1 = new Run();
Text objText_1 = new Text() { Space = SpaceProcessingModeValues.Preserve };
objText_1.Text = "Página ";
objRun_1.Append(objText_1);
objParagraph_1.Append(objRun_1);
Run objRun_2 = new Run();
FieldChar objFieldChar_1 = new FieldChar() { FieldCharType = FieldCharValues.Begin };
objRun_2.Append(objFieldChar_1);
objParagraph_1.Append(objRun_2);
Run objRun_3 = new Run();
FieldCode objFieldCode_1 = new FieldCode();
objFieldCode_1.Text = "PAGE";
objRun_3.Append(objFieldCode_1);
objParagraph_1.Append(objRun_3);
Run objRun_6 = new Run();
FieldChar objFieldChar_3 = new FieldChar() { FieldCharType = FieldCharValues.End };
objRun_6.Append(objFieldChar_3);
objParagraph_1.Append(objRun_6);
Run objRun_7 = new Run();
Text objText_3 = new Text() { Space = SpaceProcessingModeValues.Preserve };
objText_3.Text = " de ";
objRun_7.Append(objText_3);
objParagraph_1.Append(objRun_7);
Run objRun_8 = new Run();
FieldChar objFieldChar_4 = new FieldChar() { FieldCharType = FieldCharValues.Begin };
objRun_8.Append(objFieldChar_4);
objParagraph_1.Append(objRun_8);
Run objRun_9 = new Run();
FieldCode objFieldCode_2 = new FieldCode();
objFieldCode_2.Text = "NUMPAGES";
objRun_9.Append(objFieldCode_2);
objParagraph_1.Append(objRun_9);
Run objRun_12 = new Run();
FieldChar objFieldChar_6 = new FieldChar() { FieldCharType = FieldCharValues.End };
objRun_12.Append(objFieldChar_6);
objParagraph_1.Append(objRun_12);
objFooter.Append(objParagraph_1);
string strFootrID = objMainDocumentPart.GetIdOfPart(objFootPart);
FooterReference objFooterReference = new FooterReference()
{
Type = HeaderFooterValues.Default,
Id = strFootrID
};
objSectionProperties.Append(objFooterReference);
objBody.Append(objSectionProperties);
objMainDocumentPart.Document.Append(objBody);
}
}
I found this code here. It was a little bit buggy but it helped me a lot!
There were a few lines that i thought it was unnecessary so i removed it and worked great, but i'm only a newbie in openXML so maybe they were in fact necessary.
Cheers!
The Open Xml SDK does NOT provide application behaviors such as layout (ex. pagination of WordprocessingML documents) or recalculation functionality. You can read more # http://blogs.msdn.com/b/brian_jones/archive/2008/10/06/open-xml-format-sdk-2-0.aspx

Categories