Reputation: 35
In my C# Desktop app i am using the Microsoft.Office.Interop.Word
library to write to a word file. But whenever its done exporting there's huge spaces between paragraphs. Using the paragraph1.Range.ParagraphFormat.SpaceAfter = 0;
parameter doesn't affect the result as well.
My desired result is the "No Spacing" preset in Word but after some research i found out it is not an option this library.
Is there any way to remove or set the spacing between paragraphs.
This is my code:
Microsoft.Office.Interop.Word.Application word = new Application();
word.Visible = false;
var doc = word.Documents.Add();
var paragraph1 = doc.Content.Paragraphs.Add();
paragraph1.Range.Font.Name = "Calibri";
paragraph1.Range.Font.Size = 11;
paragraph1.Range.ParagraphFormat.SpaceBefore = 0;
paragraph1.Range.ParagraphFormat.SpaceAfter = 0;
paragraph1.Range.Text = story;
paragraph1.Range.InsertParagraphAfter();
doc.SaveAs2(@"F:\Documents\Visual Studio Projects\LITPC\LITPC\bin\Debug\"+title+".docx");
word.Quit();
Upvotes: 1
Views: 2732
Reputation: 11
I solved this problem by changing the Word.Paragraph.SpaceAfter
parameter on previous paragraph. For example.
// First Paragraph
Word.Paragraph mainTitle = document.Paragraphs.Add();
mainTitle.Range.Text = "para1";
mainTitle.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
mainTitle.Range.InsertParagraphAfter();
mainTitle.SpaceAfter = 0.0f;
// Second Paragraph
Word.Paragraph semiTitle = document.Paragraphs.Add();
semiTitle.Range.Text = "para2";
semiTitle.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
semiTitle.Range.InsertParagraphAfter();
semiTitle.SpaceAfter = 10.0f;
So, the SpaceAfter
of semiTitle
will be 0. Similarly, the SpaceAfter
of the next paragraph after semiTitle
will be 10.
Upvotes: 1
Reputation: 32
First of all the SpaceBefore
and SpaceAfter
properties take floats so you need to suffix your values with an f.
Try: paragraph1.SpaceBefore = 0.0f;
, that worked for me.
Also, be careful to reset the spacing when you insert a new paragraph because subsequent paragraphs will inherit the new spacing.
Or avoid Interop Word altogether if you can, it's a deep, dark, rabbit hole I've been down for several days.
Upvotes: 1