Change word document body font and Footnotes font - c#

I have MS Word document how can I change it body font to "Arial" and Footnotes font to "Times New Roman" using C# , (Interop.Word or any free library).
I Did Search a lot before posting this Question.. But find nothing.
I found this Question but it dose not really help
How to search for a specific font in a Word document with iterop

This is some sample code. I have set the font for both body text and footnote text. The code reads "test.doc" from C drive.
using System;
using Microsoft.Office.Interop.Word;
namespace Word
{
class Program
{
static void Main(string[] args)
{
Application wordApp = new Application();
string filename = #"C:\test.doc";
Document myDoc = wordApp.Documents.Open(filename);
if (myDoc.Paragraphs.Count > 0)
{
foreach (Paragraph p in myDoc.Paragraphs)
{
p.Range.Font.Name = "Calibri";
p.Range.Text = "I have changed this text I entered previously";
}
}
if (myDoc.Footnotes.Count > 0)
{
foreach (Footnote fn in myDoc.Footnotes)
{
fn.Range.Font.Name = "Arial";
}
}
myDoc.Save();
myDoc.Close();
myDoc = null;
wordApp.Quit();
wordApp = null;
}
}
}
If you are looking for MSDN documentation on using Word Interop then this is the link.

Related

C# itextsharp - Create PDF, Create Folder within Folder, Place PDF in deepest Folder

I am a complete beginner in C# and I was looking for some help regarding this project I have to make.
I am using Windows Forms and itextsharp alongside Microsoft Access. My objective is to make the program, after the user interacted with the DataGridView and filed some information on text boxes, create a PDF file (with the DataGridView on it) and then create a Folder (with name being a Machine ID given by the user before) within a Folder (with name being Client ID given by the user before) to allocate the PDF in.
This code only formats the DataGridView slightly and saves the PDF (by asking the user where).
public void exportgridtopdf(DataGridView dgw, string filename)
{
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
PdfPTable pdftable = new PdfPTable(new float[] { 1, 4, 1, 1, 1 });
pdftable.DefaultCell.Padding = 3;
pdftable.WidthPercentage = 100;
pdftable.HorizontalAlignment = Element.ALIGN_LEFT;
pdftable.DefaultCell.BorderWidth = 1;
iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
//add header
foreach (DataGridViewColumn column in dgw.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdftable.AddCell(cell);
}
//add datarow
foreach (DataGridViewRow row in dgw.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
pdftable.AddCell(new Phrase(cell.Value.ToString(), text));
}
}
var savefiledialoge = new SaveFileDialog();
savefiledialoge.FileName = filename;
savefiledialoge.DefaultExt = ".pdf";
if (savefiledialoge.ShowDialog() == DialogResult.OK)
{
using (FileStream stream = new FileStream(savefiledialoge.FileName, FileMode.Create))
{
Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfdoc, stream);
pdfdoc.Open();
pdfdoc.Add(pdftable);
pdfdoc.Close();
stream.Close();
}
}
}
The most similar case that I found was here: How to insert files into folders of an existing PDF portfolio with folders using iTextsharp
I tried implementing (what I thought I could use) but I couldn't get any reference for it or any actual progress towards my goal.
public class FolderWriter
{
private const string Folder = #"C:\Path\to\your\pdf\files";
private const string File1 = #"Pdf File 1.pdf";
private readonly string file1Path = Path.Combine(Folder, File1);
private readonly string[] keys = new[] {
"Type",
"File"
};
}
I am sorry for my lack of knowledge and for possibly little information given. I can try to upload more code if you need something specific.
Thanks in advance,
Filipe Almeida
Find the sourcecode below.
For some explanation.
First I'm creating a couple of variables like folder1, folder2InsideFolder2 and fileName.
The resulting structure is goint to look like this: folder1\folder2\pdffile.pdf
You can basically set my variables to the inputs you already got, like Machine ID, Client ID etc.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
string folder1 = "DocumentName"; // AKA Machine ID
string folder2InsideFolder1 = "SomeID"; // AKA Client ID
string fileName = "FancyPDFDocument2000.pdf";
// The next line is building a of the two outside folders where the .pdf file will be placed in
string directoryName = Path.Combine(folder1, folder2InsideFolder1);
// directoryName is now: DocumentName\SomeID\
// Let's try to create the directory
try
{
// This line creates the directory using the path that was just created
Directory.CreateDirectory(directoryName);
}
catch(Exception e)
{
// Risen when directory couldn't be created see documentation of Directory.CreateDirectory
}
// now create the final path consisting of both directories and the .pdf file name
string finalFilePath = Path.Combine(directoryName, fileName);
// finalFilePath is now: DocumentName\SomeID\FancyPDFDocument2000.pdf
// From here on you can use your remaining code to generate the .pdf file you can use the variable finalFilePath for that
}
}
}

How to write Arabic text using MigraDoc?

I am using ASP for this and I had to generate reports in PDF format and send the file back to clients so they can download it.
I made the reports using MigraDoc library and they were great but after I tried it with Arabic text I found the texts were in LTR and the characters were disjointed so I made this code to test things out
...............
MigraDoc.DocumentObjectModel.Document reportDoc = new MigraDoc.DocumentObjectModel.Document();
reportDoc.Info.Title = "test";
sec = reportDoc.AddSection();
string fileName = "test.pdf";
addformattedText(sec, "العبارة", true);
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = reportDoc;
renderer.RenderDocument();
MemoryStream pdfStream = new MemoryStream();
renderer.PdfDocument.Save(pdfStream);
byte[] bytes = pdfStream.ToArray();
...............
private void addformattedText(Section sec,string text, bool shouldBeBold = false)
{
var tf = sec.AddTextFrame();
var p = tf.AddParagraph(text);
p.Format.Font.Name = "Tahoma";
if (shouldBeBold) p.Format.Font.Bold = true;
}
I get the output like this
I have tried to encode the text and make it a unicode string using this code
private string getEscapedString(string text)
{
if (true || HasArabicCharacters(text))
{
string uString = "";
byte[] utfBytes = Encoding.Unicode.GetBytes(text);
foreach (var u in utfBytes)
{
if (u != 0)
{
uString += String.Format(#"\u{0:x4}", u);
}
}
return uString;
}
else
return text;
}
and get the returned string into a paragraph and save the PDF documents with unicode parameter set to true
But it is all the same.
I can not figure out how to get it done.
The reports were done using MigraDoc 1.50.5147 library.
The problem is Arabic language font have 4 different shap in begging,last,connected and alone, where Pdfsharp and MigraDoc can not recognize which shap to print farther more you need to reverse the character order to solve this you can use AraibcPdfUnicodeGlyphsResharper to help do such work as following:
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using AraibcPdfUnicodeGlyphsResharper;
namespace MigraDocArabic
{
internal class PrintArabicUsingPdfSharp
{
public PrintArabicUsingPdfSharp(string path)
{
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Arial", 20, XFontStyle.BoldItalic);
var xArabicString = "كتابة اللغة العربية شيئ جميل".ArabicWithFontGlyphsToPfd();
// Draw the text
gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
gfx.DrawString(xArabicString, font, XBrushes.Black, new XRect(50, 50, page.Width, page.Height), XStringFormats.Center);
// Save the document...
document.Save(path);
}
}
}
Do not Forget the Extension method
By the way this is work with iText7 too
see the image for result
Result
PDFsharp does not support RTL languages yet:
http://www.pdfsharp.net/wiki/PDFsharpFAQ.ashx#Does_PDFsharp_support_for_Arabic_Hebrew_CJK_Chinese_Japanese_Korean_6
You can work around this limitation by reversing the string.
PDFsharp does not support font ligatures yet. You are probably able to work around this limitation by replacing letters with the correct glyph (start, middle, end) depending on the position.

C# OpenXML How to Replace \r\n with Break()?

I have a text field in my database and it has a text with many lines.
When generating a MS Word document using OpenXML and bookmarks, the text become one single line.
I've noticed that in each new line the bookmark value show the characters "\r\n".
Looking for a solution, I've found some answers which helped me, but I'm still having a problem.
I've used the run.Append(new Break()); solution, but the text replaced is showing the name of the bookmark as well.
For example:
bookmark test = "Big text here in first paragraph\r\nSecond paragraph".
It is shown in MS Word document like:
testBig text here in first paragraph
Second paragraph
Can anyone, please, help me to eliminate the bookmark name?
Here is my code:
public void UpdateBookmarksVistoria(string originalPath, string copyPath, string fileType)
{
string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
// Make a copy of the template file.
File.Copy(originalPath, copyPath, true);
//Open the document as an Open XML package and extract the main document part.
using (WordprocessingDocument wordPackage = WordprocessingDocument.Open(copyPath, true))
{
MainDocumentPart part = wordPackage.MainDocumentPart;
//Setup the namespace manager so you can perform XPath queries
//to search for bookmarks in the part.
NameTable nt = new NameTable();
XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("w", wordmlNamespace);
//Load the part's XML into an XmlDocument instance.
XmlDocument xmlDoc = new XmlDocument(nt);
xmlDoc.Load(part.GetStream());
//pega a url para exibir as fotos
string url = HttpContext.Current.Request.Url.ToString();
string enderecoURL;
if (url.Contains("localhost"))
enderecoURL = url.Substring(0, 26);
else if (url.Contains("www."))
enderecoURL = url.Substring(0, 24);
else
enderecoURL = url.Substring(0, 20);
//Iterate through the bookmarks.
int cont = 56;
foreach (KeyValuePair<string, string> bookmark in bookmarks)
{
var res = from bm in part.Document.Body.Descendants<BookmarkStart>()
where bm.Name == bookmark.Key
select bm;
var bk = res.SingleOrDefault();
if (bk != null)
{
Run bookmarkText = bk.NextSibling<Run>();
if (bookmarkText != null) // if the bookmark has text replace it
{
var texts = bookmark.Value.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
for (int i = 0; i < texts.Length; i++)
{
if (i > 0)
bookmarkText.Append(new Break());
Text text = new Text();
text.Text = texts[i];
bookmarkText.Append(text); //HERE IS MY PROBLEM
}
}
else // otherwise append new text immediately after it
{
var parent = bk.Parent; // bookmark's parent element
Text text = new Text(bookmark.Value);
Run run = new Run(new RunProperties());
run.Append(text);
// insert after bookmark parent
parent.Append(run);
}
bk.Remove(); // we don't want the bookmark anymore
}
}
//Write the changes back to the document part.
xmlDoc.Save(wordPackage.MainDocumentPart.GetStream(FileMode.Create));
wordPackage.Close();
}}

Defining paragraph with RTL direction in word file by OpenXML in C#

How to set the right-to-left direction for a paragraph in word with OpenXML in C#? I use codes below to define it but they won't make any change:
RunProperties rPr = new RunProperties();
Style style = new Style();
style.StyleId = "my_style";
style.Append(new Justification() { Val = JustificationValues.Right });
style.Append(new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft });
style.Append(rPr);
and at the end I will set this style for my paragraph:
...
heading_pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "my_style" };
But is see no changes in the output file.
I have found some post but they didn't help me at all,like:
Changing text direction in word file
How can solve this problem?
Thanks in advance.
Use the BiDi class to set the text direction to RTL for a paragraph.
The following code sample searches for the first paragraph in a word document
and sets the text direction to RTL using the BiDi class:
using (WordprocessingDocument doc =
WordprocessingDocument.Open(#"test.docx", true))
{
Paragraph p = doc.MainDocumentPart.Document.Body.ChildElements.First<Paragraph>();
if(p == null)
{
Console.Out.WriteLine("Paragraph not found.");
return;
}
ParagraphProperties pp = p.ChildElements.First<ParagraphProperties>();
if (pp == null)
{
pp = new ParagraphProperties();
p.InsertBefore(pp, p.First());
}
BiDi bidi = new BiDi();
pp.Append(bidi);
}
There are a few more aspects to bi-directional text in Microsoft Word.
SanjayKumarM wrote an article about how right-to-left text content
is handled in Microsoft Word. See this link for more information.
This code worked for me to set the direction Right to Left
var run = new Run(new Text("Some text"));
var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(run);
paragraph.ParagraphProperties = new ParagraphProperties()
{
BiDi = new BiDi(),
TextDirection = new TextDirection()
{
Val = TextDirectionValues.TopToBottomRightToLeft
}
};

how to Wrap Text across an image in docx file in c#

I am making a docx generator using Docx.dll. So far i have been able to insert images and text into the document. The images and paragraph are not aligned. I need to wrap text the image. How do i do it?
I looked for it in google and found this link
Adding Images to Documents in Word 2007 by Using the Open XML SDK 2.0. The code is working and creating the word document too, but the docx file is not opening.
How do i wrap text 'In Front Of Text' in c#?
public static DocX CreateDocumentFile(List<CompanyInfo> info)
{
DocX document = DocX.Load(#"C:\Users\newton.sheikh\Documents\Visual Studio 2010\Projects\MSOffice\OpenXML\OpenXML\RetailWrite.docx");
foreach (var companies in info)
{
Formatting fm = new Formatting();
/*Inserting Image*/
Novacode.Image img = document.AddImage(#"C:\Users\newton.sheikh\Documents\Visual Studio 2010\Projects\MSOffice\OpenXML\OpenXML\logos\slime.png");
Novacode.Paragraph companyLogo = document.InsertParagraph("");
Picture pic1 = img.CreatePicture();
companyLogo.InsertPicture(pic1, 0);
Novacode.Paragraph CompanyName = document.InsertParagraph(companies.Name.ToString());
CompanyName.StyleName = "COMPANY";
Novacode.Paragraph CompanyPosition = document.InsertParagraph(companies.Position.ToString());
CompanyPosition.StyleName = "posit";
Novacode.Paragraph CompanyDescription = document.InsertParagraph(companies.Description.ToString());
CompanyDescription.StyleName = "descrip";
Novacode.Paragraph blankPara = document.InsertParagraph(" ");
Novacode.Paragraph blankPara2 = document.InsertParagraph(" ");
}
return document;
}
Solution to the problem: I used the Interop of MS-Word to apply word-wrap across images.
public static void FormatImages()
{
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
string filePath = #"C:\Users\newton.sheikh\Documents\Visual Studio 2010\Projects\MSOffice\OpenXML\OpenXML\Temp.docx";
Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(filePath, false);
object save_changes = false;
foreach (Microsoft.Office.Interop.Word.InlineShape item in wordApp.ActiveDocument.InlineShapes)
{
if (item != null)
{
if (item.Type == Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapePicture)
{
item.Select();
Microsoft.Office.Interop.Word.Shape shape = item.ConvertToShape();
shape.WrapFormat.Type = WdWrapType.wdWrapFront;
}
}
}
doc.SaveAs(#"C:\Users\newton.sheikh\Documents\Visual Studio 2010\Projects\MSOffice\OpenXML\OpenXML\RetailWrite.docx");
doc.Close(save_changes);
wordApp.Quit(save_changes);
if (System.IO.File.Exists(#"C:\Users\newton.sheikh\Documents\Visual Studio 2010\Projects\MSOffice\OpenXML\OpenXML\Temp.docx"))
{
System.IO.File.Delete(#"C:\Users\newton.sheikh\Documents\Visual Studio 2010\Projects\MSOffice\OpenXML\OpenXML\Temp.docx");
}
}

Categories