OpenXML ComplexScript font not rendering - c#

I have the following program that generates an example word document:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace OpenXmlExample
{
class Program
{
static void Main(string[] args)
{
string filePath = #"C:\Users\[Redacted]\Desktop\OpenXmlExample.docx";
using (WordprocessingDocument document = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
{
// Create main part and body of document
MainDocumentPart mainPart = document.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
// Prototype code for generation of the document title
Paragraph paragraph = new Paragraph();
ParagraphProperties pPr = new ParagraphProperties
{
Justification = new Justification { Val = JustificationValues.Center }
};
RunProperties rPr = new RunProperties
{
RunFonts = new RunFonts { ComplexScript = new StringValue("Arial") },
Bold = new Bold { Val = true },
Caps = new Caps { Val = true },
FontSize = new FontSize { Val = "32" },
FontSizeComplexScript = new FontSizeComplexScript { Val = "36" }
};
Text t = new Text("Example Document");
Run r = new Run();
r.Append((OpenXmlElement) rPr.Clone());
r.Append(t);
pPr.Append((OpenXmlElement) rPr.Clone());
paragraph.Append(pPr);
paragraph.Append(r);
body.Append(paragraph);
}
}
}
}
It seems to be working just fine. "EXAMPLE DOCUMENT" is rendered properly, bold and uppercase, with 16pt font. However, the ComplexScript = new StringValue("Arial") part doesn't seem to be working. The text is just rendered in the default font. Can anyone help me to understand if I'm doing something incorrectly? It seems to work if I set the Ascii property to Arial, but I would like it to be generated as a <w:rFonts w:cs="Arial"/> tag.

For a single run, 4 different fonts can be configured.
The use of each of these fonts shall be determined by the Unicode character values of the run content.
ASCII for characters in the Unicode range (U+0000-U+007F).
Complex Script for characters in a complex script Unicode range, eg. Arabic text.
East Asian for characters in an East Asian Unicode range, eg. Japanese.
High ANSI for characters in a Unicode range which does not fall into one of the other categories.
The characters in 'EXAMPLE DOCUMENT' all fall within the ASCII group and will therefore have font of the corresponding group applied.
More details at MSDN and Office Open XML.

Related

Hebrew characters are printed in reverse order in iText 7

I'm using iText 7 for printing some text in List (in Hebrew) to PDF file, but while printing the Hebrew characters are printed in a reverse way.
The input given was "קניון אם הדרך" while the data printed in PDF is "ךרדה םא ןוינק"
I have set the font encoding and the base direction for the elements but still the characters are printed in the reverse order.
Code to print list into the table in PDF:
public void PrintListData(string filename)
{
var writer = new PdfWriter(filename);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc, PageSize.A4);
SetFont(doc);
Table table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();
table.SetTextAlignment(TextAlignment.RIGHT);
//table.SetBaseDirection(BaseDirection.RIGHT_TO_LEFT);
var index = 1;
foreach (var item in _data)
{
var para = new Paragraph(item);
para.SetTextAlignment(TextAlignment.RIGHT);
//para.SetBaseDirection(BaseDirection.RIGHT_TO_LEFT);
table.AddCell(index.ToString());
table.AddCell(para);
index++;
}
doc.Add(table);
doc.Close();
Process.Start(filename);
}
Set font function
void SetFont(Document doc)
{
FontSet _defaultFontSet = new FontSet();
var fontFolders = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
_defaultFontSet.AddFont(System.IO.Path.Combine(fontFolders, "arial.ttf"), PdfEncodings.IDENTITY_H);
_defaultFontSet.AddFont(System.IO.Path.Combine(fontFolders, "arialbd.ttf"), PdfEncodings.IDENTITY_H);
doc.SetFontProvider(new FontProvider(_defaultFontSet));
doc.SetProperty(Property.FONT, new String[] { "MyFontFamilyName" });
//doc.SetProperty(Property.BASE_DIRECTION, BaseDirection.RIGHT_TO_LEFT);
}
I'm not sure to where should we set the text direction to print RTL.

How to Align Paragraph in Center using OpenXml C# for PPT?

I'm trying to align my paragraph in the center for ppt but its not working!
This is my code:
public static void ChangeSlidePart(SlidePart slidePart1,PresentationPart presentationPart)
{
Slide slide1 = slidePart1.Slide;
CommonSlideData commonSlideData1 = slide1.GetFirstChild<CommonSlideData>();
ShapeTree shapeTree1 = commonSlideData1.GetFirstChild<ShapeTree>();
Shape shape1 = shapeTree1.GetFirstChild<Shape>();
TextBody textBody1 = shape1.GetFirstChild<TextBody>();
D.Paragraph paragraph1 = textBody1.GetFirstChild<D.Paragraph>();
D.Run run1 = paragraph1.GetFirstChild<D.Run>();
run1.RunProperties= new D.RunProperties() {FontSize = 6600};
run1.RunProperties.Append(new D.LatinFont() { Typeface = "Arial Black" });
//run1.Append(runProperties1);
D.Text text1 = run1.GetFirstChild<D.Text>();
text1.Text = "Good day";
}
I tried adding to this paragraph properties with the corresponding justification but nothing was updated.
It doesn't seem that easy to do this using Open XML SDK. With Aspose.Slides for .NET, you can align a paragraph as shown below:
// The presentation variable here is an instance of the Presentation class.
var firstShape = (IAutoShape) presentation.Slides[0].Shapes[0];
var firstParagraph = firstShape.TextFrame.Paragraphs[0];
firstParagraph.ParagraphFormat.Alignment = TextAlignment.Center;
You can also evaluate Aspose.Slides Cloud SDK for .NET. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to align a paragraph using Aspose.Slides Cloud:
var slidesApi = new SlidesApi("my_client_id", "my_client_key");
var filePath = "example.pptx";
var slideIndex = 1;
var shapeIndex = 1;
var paragraphIndex = 1;
var paragraph = slidesApi.GetParagraph(
filePath, slideIndex, shapeIndex, paragraphIndex);
paragraph.Alignment = Paragraph.AlignmentEnum.Center;
slidesApi.UpdateParagraph(
filePath, slideIndex, shapeIndex, paragraphIndex, paragraph);
I work as a Support Developer at Aspose.

Draw checked box with itextsharp

how can I draw checked box (with X) with iTextSharp.
I don't want it to be image. More like symbol
I tried this, but it didn't work:
RadioCheckField fCell = new RadioCheckField(writer, new Rectangle(20,20), "NoDeletion", "Yes");
fCell.CheckType = RadioCheckField.TYPE_CROSS;
PdfFormField footerCheck = null;
footerCheck = fCell.CheckField;
writer.AddAnnotation(footerCheck);
Thanks,
I assume that you don't need an interactive check box. You just want to use a check box character. The first thing you need, is a font that has such a character. When I work on Windows, I have access to a file named WINGDING.TTF. This is a font program that contains all kinds of symbols, among others some check boxes:
I created the PDF shown in the screen shot like this:
public static final String DEST = "results/fonts/checkbox_character.pdf";
public static final String FONT = "c:/windows/fonts/WINGDING.TTF";
public static final String TEXT = "o x \u00fd \u00fe";
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.GetInstance(document, new FileOutputStream(dest));
document.Open();
BaseFont bf = BaseFont.CreateFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);
Paragraph p = new Paragraph(TEXT, f);
document.Add(p);
document.Close();
}
As you can see, the empty check box corresponds with the letter o, there are three variations of a checked check box.
Thank you, but I found a solution. Here it is:
var checkBox = new Phrase();
checkBox.Add(new Chunk(" ☒ ", new Font(BaseFont.CreateFont(PrintCommonConstants.UnicodeFontNormal, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 18)));

How to get rid of my "After Spacing" on open xml

In open XML my word document defaults to having "Spacing After: 10 pt" How would I change it to 0, so there is no spacing.
Here is my code, which pretty much grabs the information from a database and places it onto a word document to be able to print out. But the spacing is making the document too big.
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) {
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para_main = body.AppendChild(new Paragraph());
Run run_main = para_main.AppendChild(new Run());
// Goes through all of the forms
foreach (var form in forms) {
Table table = new Table();
// Initialize all of the table properties
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 8 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 8 }
),
new SpacingBetweenLines() { Before = "20", After = "20" }
//new TableCellProperties(
// new
//new TableJustification() {Val = TableRowAlignmentValues.Center}
);
table.AppendChild<TableProperties>(tblProp);
Paragraph para_header = body.AppendChild(new Paragraph());
Run run_header = para_header.AppendChild(new Run());
RunProperties runProps = run_header.AppendChild(new RunProperties(new Bold()));
string username = form.Username;
string proces_header = form.HeaderTitle;
run_header.AppendChild(new Text(proces_header + " | " + username));
for (int i = 0; i < form.FieldList.Count; i++) {
if (!(form.FieldList[i].Token == "USR" || form.FieldList[i].Token == "SNT")) {
TableRow tr = new TableRow();
TableCell header_cell = new TableCell();
header_cell.Append(new Paragraph(new Run(new Text(form.FieldList[i].Label))));
TableCell value_cell = new TableCell();
value_cell.Append(new Paragraph(new Run(new Text(form.FieldList[i].Value))));
tr.Append(header_cell, value_cell);
table.Append(tr);
}
}
wordDoc.MainDocumentPart.Document.Body.Append(table);
}
mainPart.Document.Save();
wordDoc.Close();
return "Success";
}
The line spacing needs to be appended to the paragraph properties and of course that needs to be appended to the paragraph.
Here is the long way to do it. The SpacingBetweenLines can also set the line height and the "rules" control how the before and after values are used.
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);
It looks like you are trying to set the line spacing to the table. That will not work that way(believe me I tried). Text around the table is controlled by the text wrapping and the positioning of the table.
Also when working with multiple tables, if you want to keep them separated there needs to be a paragraph(or something other then a table) after the table, otherwise your tables we merge together.
If you need that space create a paragraph with the font set to .5 or something really small and just add it after each table.

iTextSharp setting font family to chunk

Because I use dynamic text, italic or bold text could be any where, cutting everything into chunks is not an option, so I have to use html parser.
Input string is
ąčęėįšųū90-žthis <i>is <b>bold ąčęėįšųū90-ž</i></b> text
String is formatted with iTextSharp html parser:
private Paragraph CreateSimpleHtmlParagraph(String text)
{
//Our return object
List<Chunk> c = new List<Chunk>();
Paragraph p = new Paragraph();
var styles = new StyleSheet();
using (StringReader sr = new StringReader(text))
{
//Parse and get a collection of elements
List<IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, styles);
foreach (IElement e in elements)
{
var chunks = e.Chunks;
foreach (var chunk in chunks) //list of chunks
{
chunk.Font.SetFamily(""); //how to set font family here
}
p.Add(e);
}
}
return p; //getting all the special chars (ąčęėįšųū90-ž...)
}
Code in the main form:
Paragraph pr1 = CreateSimpleHtmlParagraph("ąčęėįšųū90-žthis <i>is <b>bold ąčęėįšųū90-ž</i></b> text");
doc.Add(pr1);
But in PDF I see only
š90-žthis is bold š90-ž text
and no other chars (ąčęėį). I know it has something to do with Fonts, but can't find the problem where. The font should be the same for whole document, times new roman, arial, ect., anything, that could show me my special chars (cp1257, Baltic encoding).
Usually, when I have to format text I use Chunks and my own fonts:
Font arial10n = PdfFontManager.GetFont("c:\\windows\\fonts\\arial.ttf", 10);
colClientTxt.AddText(new Chunk(row["name"].ToString() + "\n", arial10n));
and in PdfFontManager class:
public static Font GetFont(string name, int size)
{
BaseFont baseFont = BaseFont.CreateFont(name, BaseFont.CP1257, BaseFont.EMBEDDED);
Font font = new Font(baseFont, size);
return font;
}
So, how to set font family, or maybe there is another way to dinamicaly format my text?

Categories

Resources