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

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.

Related

i cant insert section break in aspose.word after add header

after insert header in aspose.word I want insert BreackNewPage
but
Exception occurred when insert section break in aspose.word for .Net
my Code Is in here:
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
Shape shape = builder.InsertImage(dataDir);
shape.Height = builder.PageSetup.PageHeight - 200;
shape.Width = builder.PageSetup.PageWidth - 50;
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPositionRelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;
builder.InsertBreak(BreakType.SectionBreakNewPage);
Your cursor needs to be inside the "main Story" to be able to insert the requested break. Please see following code:
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
Shape shape = builder.InsertImage(MyDir + #"aspose.words.jpg");
shape.Height = builder.PageSetup.PageHeight - 200;
shape.Width = builder.PageSetup.PageWidth - 50;
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;
builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.SectionBreakNewPage);
doc.Save(MyDir + #"17.11.docx");
I work with Aspose as Developer Evangelist.
You can use a simple function provided by aspose.word as
Document doc = new Document();
DocumentBuilder documentBuilder= new DocumentBuilder(doc);
documentBuilder.MoveToDocumentEnd(); //moving cursor to end of page.
documentBuilder.InsertBreak(BreakType.SectionBreakNewPage); // creating new page.
documentBuilder.PageSetup.ClearFormatting(); //clear formatting.

WPF: The font will not change on a printed FlowDocument

I am trying to print the contents of a rich-text box. I do that in the following way:
Obtain a TextRange from the FlowDocument.
Create a new FlowDocument with a smaller font using the TextRange.
Send this new FlowDocument to the printer.
My problem, is that the font doesn't seem to change. I would like it to go down to size 8. Instead, it remains at a fixed size. Here is my code:
private void button_Print_Click(object sender, RoutedEventArgs e)
{
IDocumentPaginatorSource ps = null;
FlowDocument fd = new FlowDocument();
PrintDialog pd = new PrintDialog();
Paragraph pg = new Paragraph();
Style style = new Style(typeof(Paragraph));
Run r = null;
string text = string.Empty;
// get the text
text = new TextRange(
this.richTextBox_Info.Document.ContentStart,
this.richTextBox_Info.Document.ContentEnd).Text;
// configure the style of the flow document
style.Setters.Add(new Setter(Block.MarginProperty, new Thickness(0)));
fd.Resources.Add(typeof(Paragraph), style);
// style the paragraph
pg.LineHeight = 0;
pg.LineStackingStrategy = LineStackingStrategy.BlockLineHeight;
pg.FontFamily = new FontFamily("Courier New");
pg.TextAlignment = TextAlignment.Left;
pg.FontSize = 8;
// create the paragraph
r = new Run(text);
r.FontFamily = new FontFamily("Courier New");
r.FontSize = 8;
pg.Inlines.Add(r);
// add the paragraph to the document
fd.Blocks.Add(pg);
ps = fd;
// format the page
fd.PagePadding = new Thickness(50);
fd.ColumnGap = 0;
fd.ColumnWidth = pd.PrintableAreaWidth;
// print the document
if (pd.ShowDialog().Value == true)
{
pd.PrintDocument(ps.DocumentPaginator, "Information Box");
}
}
I would like to add that, changing the font works just fine for the flow-document when it is inside of the rich-text box. However, when I am doing it programmatically (as shown above) I run into problems.
I try your code and found when I remove this line and then change the r.FontSize to 50, it seems work.
pg.LineHeight = 0;

WPF FlowDocument printing only to small area

I am printing plain text in WPF by using a FlowDocument, FlowDocumentPaginator and PrintDialog. My approach is based on this article and is implemented as follows:
var printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
var flowDocument = new FlowDocument();
var paragraph = new Paragraph();
paragraph.FontFamily = new FontFamily("Courier New");
paragraph.FontSize = 10;
paragraph.Margin = new Thickness(0);
paragraph.Inlines.Add(new Run(this.textToPrint));
flowDocument.FontSize = 10;
flowDocument.Blocks.Add(paragraph);
var paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
printDialog.PrintDocument(paginator, "Chit");
}
This works good for printing stuff with narrow width. But when I try to print a long string, it all gets stuffed in a small area:
I checked dimensions in the print dialog's PrintTicket and in the paginator, and they seem to be okay:
So, what is causing this problem and how can I fix it?
This is some code I use
flowDocument.PagePadding = new Thickness(standardThickness);
flowDocument.ColumnGap = 0;
flowDocument.ColumnWidth = printDialog.PrintableAreaWidth;
You need to tell the flowdocument it is one column and tell the flowdocument the width of the printer.

How to introduce superscript in iTextSharp?

I want the output format date like 14th may 2015. the th in 14 it should come with sup tag but sup tag is not accessing here. the output i am getting in ph102 variable. Getsuffix(csq.EventDate.Value.Day) in this only i am getting suffix of th st and rd for date
My code:
PdfPTable table9 = new PdfPTable(4);
table9.WidthPercentage = 99;
table9.DefaultCell.Border = 0;
table9.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
Phrase ph101 = new Phrase("Event Date & Time", textFont2);
PdfPCell cellt1 = new PdfPCell(ph101);
cellt1.Border = PdfPCell.BOTTOM_BORDER + PdfPCell.LEFT_BORDER + PdfPCell.RIGHT_BORDER;
cellt1.PaddingTop = 0F;
cellt1.VerticalAlignment = Element.ALIGN_MIDDLE;
cellt1.HorizontalAlignment = Element.ALIGN_LEFT;
DateTime eventTime = DateTime.Today;
if (!string.IsNullOrEmpty(Convert.ToString(csq.EventTime)))
eventTime = DateTime.Today.Add(csq.EventTime.Value);
Phrase ph102;
if (!string.IsNullOrEmpty(csq.EventDate.ToString()))
{
ph102 = new Phrase(csq.EventDate.Value.Day + Getsuffix(csq.EventDate.Value.Day) + csq.EventDate.Value.ToString("MMM") + " " + csq.EventDate.Value.Year + " at " + eventTime.ToString("hh:mm tt"), textFont7);
}
else
{
ph102 = new Phrase();
}
PdfPCell cellt2 = new PdfPCell(ph102);
cellt2.Border = PdfPCell.BOTTOM_BORDER + PdfPCell.LEFT_BORDER + PdfPCell.RIGHT_BORDER;
cellt2.PaddingTop = 0F;
cellt2.VerticalAlignment = Element.ALIGN_MIDDLE;
cellt2.HorizontalAlignment = Element.ALIGN_LEFT;
When I read your question, I assume that you want something like this:
However, you are confusing people as is demonstrated in the comment from somebody who gives you a hint to use HTML to PDF. Your answer is "no sir it cant work" which is a strange answer, because it can work. It's just not what you meant when you talked about sup tag. At least, that's what I assume when I look at your code, I don't see any HTML.
In your code, you create a Phrase like this:
ph102 = new Phrase(csq.EventDate.Value.Day
+ Getsuffix(csq.EventDate.Value.Day)
+ csq.EventDate.Value.ToString("MMM")
+ " " + csq.EventDate.Value.Year
+ " at " + eventTime.ToString("hh:mm tt"), textFont7);
This complete Phrase is expressed in textFont7 which can't work in your case, because you want to use a smaller font for the "st", "nd", "rd" or "th".
You need to do something like this (see OrdinalNumbers for the full example):
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
Font small = new Font(FontFamily.HELVETICA, 6);
Chunk st = new Chunk("st", small);
st.setTextRise(7);
Chunk nd = new Chunk("nd", small);
nd.setTextRise(7);
Chunk rd = new Chunk("rd", small);
rd.setTextRise(7);
Chunk th = new Chunk("th", small);
th.setTextRise(7);
Paragraph first = new Paragraph();
first.add("The 1");
first.add(st);
first.add(" of May");
document.add(first);
Paragraph second = new Paragraph();
second.add("The 2");
second.add(nd);
second.add(" and the 3");
second.add(rd);
second.add(" of June");
document.add(second);
Paragraph fourth = new Paragraph();
fourth.add("The 4");
fourth.add(rd);
fourth.add(" of July");
document.add(fourth);
document.close();
}
This is the Java code to create the PDF in the screen shot. You'll have to adapt your code so that it works in C#. As you can see, you can not just concatenate your strings using the + operator. You need to compose your Phrase or Paragraph using different Chunk objects. What you call "sup" is done by using a smaller font and a text rise.

C# Open XML HTML to DOCX Spacing

I've been working on my site, and trying to create an Export to Word. The export works well, converting HTML string to DOCX.
I'm trying to figure out how I can adjust the Line Spacing. By Default Word is adding 8pt Spacing After and setting the Line Spacing to double. I would prefer 0 and Single.
Here is the Function I created to Save a Word Document:
private static void SaveDOCX(string fileName, string BodyText, bool isLandScape, double rMargin, double lMargin, double bMargin, double tMargin)
{
string htmlSectionID = "Sect1";
//Creating a word document using the the Open XML SDK 2.0
WordprocessingDocument document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document);
//create a paragraph
MainDocumentPart mainDocumenPart = document.AddMainDocumentPart();
mainDocumenPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
Body documentBody = new Body();
mainDocumenPart.Document.Append(documentBody);
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body>" + BodyText + "</body></html>"));
// Create alternative format import part.
AlternativeFormatImportPart formatImportPart = mainDocumenPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, htmlSectionID);
//ms.Seek(0, SeekOrigin.Begin);
// Feed HTML data into format import part (chunk).
formatImportPart.FeedData(ms);
AltChunk altChunk = new AltChunk();
altChunk.Id = htmlSectionID;
mainDocumenPart.Document.Body.Append(altChunk);
/*
inch equiv = 1440 (1 inch margin)
*/
double width = 8.5 * 1440;
double height = 11 * 1440;
SectionProperties sectionProps = new SectionProperties();
PageSize pageSize;
if (isLandScape)
{
pageSize = new PageSize() { Width = (UInt32Value)height, Height = (UInt32Value)width, Orient = PageOrientationValues.Landscape };
}
else
{
pageSize = new PageSize() { Width = (UInt32Value)width, Height = (UInt32Value)height, Orient = PageOrientationValues.Portrait };
}
rMargin = rMargin * 1440;
lMargin = lMargin * 1440;
bMargin = bMargin * 1440;
tMargin = tMargin * 1440;
PageMargin pageMargin = new PageMargin() { Top = (Int32)tMargin, Right = (UInt32Value)rMargin, Bottom = (Int32)bMargin, Left = (UInt32Value)lMargin, Header = (UInt32Value)360U, Footer = (UInt32Value)360U, Gutter = (UInt32Value)0U };
sectionProps.Append(pageSize);
sectionProps.Append(pageMargin);
mainDocumenPart.Document.Body.Append(sectionProps);
//Saving/Disposing of the created word Document
document.MainDocumentPart.Document.Save();
document.Dispose();
}
In searching, I found this code:
SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };
I've placed it many places in my function, but I can't seem to find the correct place to Append this setting.
I worked on the function trying to set the spacing in code, but wasn't able to remove the spacing. I decided to try creating a Template Word Document and setting the spacing in that document.
I copy the template.docx file, creating the one I will use, then use the adjusted function below to add the HTML string:
private static void SaveDOCX(string fileName, string BodyText, bool isLandScape, double rMargin, double lMargin, double bMargin, double tMargin)
{
WordprocessingDocument document = WordprocessingDocument.Open(fileName, true);
MainDocumentPart mainDocumenPart = document.MainDocumentPart;
//Place the HTML String into a MemoryStream Object
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body>" + BodyText + "</body></html>"));
//Assign an HTML Section for the String Text
string htmlSectionID = "Sect1";
// Create alternative format import part.
AlternativeFormatImportPart formatImportPart = mainDocumenPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, htmlSectionID);
// Feed HTML data into format import part (chunk).
formatImportPart.FeedData(ms);
AltChunk altChunk = new AltChunk();
altChunk.Id = htmlSectionID;
//Clear out the Document Body and Insert just the HTML string. (This prevents an empty First Line)
mainDocumenPart.Document.Body.RemoveAllChildren();
mainDocumenPart.Document.Body.Append(altChunk);
/*
Set the Page Orientation and Margins Based on Page Size
inch equiv = 1440 (1 inch margin)
*/
double width = 8.5 * 1440;
double height = 11 * 1440;
SectionProperties sectionProps = new SectionProperties();
PageSize pageSize;
if (isLandScape)
pageSize = new PageSize() { Width = (UInt32Value)height, Height = (UInt32Value)width, Orient = PageOrientationValues.Landscape };
else
pageSize = new PageSize() { Width = (UInt32Value)width, Height = (UInt32Value)height, Orient = PageOrientationValues.Portrait };
rMargin = rMargin * 1440;
lMargin = lMargin * 1440;
bMargin = bMargin * 1440;
tMargin = tMargin * 1440;
PageMargin pageMargin = new PageMargin() { Top = (Int32)tMargin, Right = (UInt32Value)rMargin, Bottom = (Int32)bMargin, Left = (UInt32Value)lMargin, Header = (UInt32Value)360U, Footer = (UInt32Value)360U, Gutter = (UInt32Value)0U };
sectionProps.Append(pageSize);
sectionProps.Append(pageMargin);
mainDocumenPart.Document.Body.Append(sectionProps);
//Saving/Disposing of the created word Document
document.MainDocumentPart.Document.Save();
document.Dispose();
}
By using the template file, the line spacing is correct.
For those that might find this function useful, here is the code that calls the function:
string filePath = "~/Content/Exports/Temp/";
string WordTemplateFile = HttpContext.Current.Server.MapPath("/Content/Templates/WordTemplate.docx");
string DestinationPath = HttpContext.Current.Server.MapPath(filePath);
string NewFileName = DOCXFileName + ".docx";
string destFile = System.IO.Path.Combine(DestinationPath, NewFileName);
System.IO.File.Copy(WordTemplateFile, destFile, true);
SaveDOCX(destFile, HTMLString, isLandScape, rMargin, lMargin, bMargin, tMargin);
You can't change the formatting because your code is only inserting HTML into a Word doc. To change the formatting, the HTML text needs to be converted to regular text and added to the Word doc as such. I was in a similar issue and using the HtmlToOpenXml library makes this quick and simple.
using HtmlToOpenXml;
Then the function:
protected virtual void createWord()
{
string html = "*myHtml*";
// Create WordProcessingDocument
WordprocessingDocument doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = doc.MainDocumentPart;
if (mainPart == null)
mainPart = doc.AddMainDocumentPart();
Document document = doc.MainDocumentPart.Document;
if (document == null)
document = mainPart.Document = new Document();
Body body = mainPart.Document.Body;
if (body == null)
body = mainPart.Document.Body = new Body(new SectionProperties(new PageMargin() { Top = 1440, Right = 1440U, Bottom = 1440, Left = 1440U, Header = 720U, Footer = 720U, Gutter = 0U }));
// Convert Html to OpenXml
HtmlConverter converter = new HtmlConverter(mainPart);
converter.ParseHtml(html);
// Reformat paragraphs
ParagraphProperties pProps = new ParagraphProperties(new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" });
var paragraphs = doc.MainDocumentPart.Document.Body.Descendants<Paragraph>().ToList();
foreach (Paragraph p in paragraphs)
{
if (p != null)
p.PrependChild(pProps.CloneNode(true));
}
// Close the document handle
doc.Close();
}

Categories

Resources